gpt4 book ai didi

scala - 在 Scala 中分解函数

转载 作者:行者123 更新时间:2023-12-01 11:13:15 25 4
gpt4 key购买 nike

所以我有以下函数定义。

def partition[A, B, C](
partitionF: A => Either[B, C])

其中 A、B 和 C 是任意类型。

现在我定义一个函数传入

sealed trait Response
case object ThisResponse extends Response
case object ThatResponse extends Response

case object ThisDirection
case object ThatDirection

def responsePartition(response: Response):
Either[ThisDirection, ThatDirection] = response match {
case ThisResponse => Left(ThisDirection)
case ThatResponse => Right(ThatDirection)
}

然后我们将按如下方式传入

partition(responsePartition)

在业务逻辑中。

现在我试图单独获取在 responsePartition 中定义的 A => B 和 A => C 方法

所以我要找的是

val partitionFonB : A => B = ??? // This is case of this example would be ThisResponse => ThisDirection

val partitionFonC : A => C = ??? // This is case of this example would be ThatResponse => ThatDirection

有没有办法做到这一点?我尝试了右投影和左投影,但无法获得正确的类型。

最佳答案

在一般情况下,您不能从 A => 类型的函数中提取(总的)A => BA => C 函数要么 [B, C]。如果函数为特定值 a1 生成 B,则 A => C 函数不会在那里定义,反之亦然。

你能做的最好,如果你只有 A => Either[B, C]A => Option[B]A = > 选项[C](使用_.toLeft.toOption_.toOption)。

对于您的特定情况,您可以提取 ThisResponse => ThisDirectionThatResponse => ThatDirection 作为单独的函数开始,然后将它们组合起来以获得 Response => Either[ThisDirection, ThatDirection] 函数:

def thisResponse(response: ThisResponse): ThisDirection = ThisDirection // or any This-specific functionality

def thatResponse(response: ThatResponse): ThatDirection = ThatDirection // or any That-specific functionality

def responsePartition(response: Response):
Either[ThisDirection, ThatDirection] = response match {
case r:ThisResponse => Left(thisResponse(r))
case r:ThatResponse => Right(thatResponse(r))
}

关于scala - 在 Scala 中分解函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55802542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com