在Scala中分解函数

时间:2019-04-23 00:00:31

标签: 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 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

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

1 个答案:

答案 0 :(得分:5)

通常,您无法从类型A => B的函数中提取(总计)A => CA => Either[B, C]函数。如果该函数为特定值B产生一个a1,则不会在那里定义A => C函数,反之亦然。

如果您只有A => Either[B, C]A => Option[B]A => Option[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))
}