gpt4 book ai didi

scala - 如何将 PartialFunction 提升为 Either

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

Scala API 中没有内置函数可以将 PartialFunction 提升为 Either

这是我的版本:

  def liftToEither[A, B, C](pf: PartialFunction[A, B])(c: A => C) : A => Either[C, B] = { a =>
if (pf.isDefinedAt(a)) Right(pf(a)) else Left(c(a))
}

有没有更好的办法?

最佳答案

您可以使用 lifttoRight .我不确定我是否会称之为更好。

def liftToEither[A, B, C](pf: PartialFunction[A, B])(c: A => C) : A => Either[C, B] =
a => pf.lift(a).toRight(c(a))

lift将转变 PartialFunction[A, B]进入A => Option[B] .然后我们可以将提升的功能应用于 a获取Option[B] ,并使用 toRight改造 Some(b)Right(b) , 并申请 ca对于 None 的实例得到Left(c(a)) .

关于scala - 如何将 PartialFunction 提升为 Either,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28993794/

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