Scala中的函数分解

Scala中的函数分解,scala,Scala,我有下面的函数定义 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 That

我有下面的函数定义

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


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

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

如果你所能做的就是
A=>或者[B,C]
就是
A=>选项[B]
A=>选项[C]
(使用
.toLeft.toOption
.toOption


对于您的特定情况,您可以将
ThisResponse=>ThisDirection
ThatResponse=>ThatDirection
提取为单独的函数,然后将它们组合在一起以获得
Response=>ThisDirection,ThatDirection]
函数:

def thisResponse(响应:thisResponse):ThisDirection=ThisDirection//或任何此特定功能
def thatResponse(response:thatResponse):ThatDirection=ThatDirection//或任何特定功能
def响应部分(响应:响应):
[ThisDirection,ThatDirection]=响应匹配{
案例r:ThisResponse=>Left(ThisResponse(r))
案例r:ThatResponse=>Right(ThatResponse(r))
}

“对于您的特定情况,您可以将ThisResponse=>ThisDirection和ThatResponse=>ThatDirection作为单独的函数提取出来,然后将它们组合起来,得到一个响应=>ThisDirection,ThatDirection]函数。”是的,这样也可以。但是我如何在不调用任何一个函数的情况下做到这一点呢?我不确定你在这里的意思-你还有问题吗?没有,在我发布第一条评论之前,我没有得到最后一次编辑。我想这会让事情变得明朗。谢谢
val partitionFonC : A => C = ??? // This is case of this example would be ThatResponse => ThatDirection