我写了一个 Scala 函数:
def liftOrIdentity[T](f: (T, T) => T) = (a: Option[T], b: Option[T]) =>
(a, b) match {
case (Some(a), None) => Some(a)
case (None, Some(b)) => Some(b)
case (Some(a), Some(b)) => Some(f(a, b))
case (None, None) => None
}
这个图案有名字吗?由于情况 1 和 2,它不是一个适用的仿函数。请随意用 Haskell 或 Scala 代码回答。
最佳答案
收藏时是flatten
+ reduce
:
List(a, b).flatten.reduceOption(f)
a ++ b reduceOption f // same result
关于scala - 这种提升功能有名字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17188123/