1

例如,我想将一个函数f: (Int,Int) => Int应用于 type 的两个元素Option[Int]。我的想法类似于 (a,b).zipped.map(f),但这会产生一个列表,我想得到一个新的 Option[Int] 作为结果。

scala> def f(a:Int,b:Int) = a*b
f: (a: Int, b: Int)Int

scala> val x = Some(42)
x: Some[Int] = Some(42)

scala> val y:Option[Int] = None
y: Option[Int] = None

scala> (x,y).zipped.map(f)//I want None as a result here
res7: Iterable[Int] = List()

如果没有显式分支,如何做到这一点?

4

3 回答 3

6

就像 scala 中的许多其他操作一样,这可以通过理解来完成:

def f(a:Int,b:Int) = a*b
for (x <- maybeX; y <- maybeY) yield f(x, y)
于 2013-04-18T08:08:44.180 回答
1

与这类问题的情况一样,scalaz 有一些帮助:

scala> import scalaz._
import scalaz._

scala> import Scalaz._
import Scalaz._

scala> def f(a:Int,b:Int) = a*b
f: (a: Int, b: Int)Int

scala> val x = Some(42)
x: Some[Int] = Some(42)

scala> val y:Option[Int] = None
y: Option[Int] = None

scala> ^(x,y)(f)
res0: Option[Int] = None

scala> val x = 42.some
x: Option[Int] = Some(42)

scala> (x |@| y)(f)
res3: Option[Int] = None
于 2013-04-18T08:23:23.073 回答
0

使用 om-nom-nom 的想法,我可以做这样的事情:

scala> def f(a:Int,b:Int) = a*b
f: (a: Int, b: Int)Int

scala> def lifted(f: (Int,Int) => Int) = (a:Option[Int],b:Option[Int]) => for(x<-a;y<-b) yield f(x,y)
lifted: (f: (Int, Int) => Int)(Option[Int], Option[Int]) => Option[Int]

scala> def liftedF = lifted(f)
liftedF: (Option[Int], Option[Int]) => Option[Int]

scala> val x = Some(42)
x: Some[Int] = Some(42)

scala> val y:Option[Int] = None
y: Option[Int] = None

scala> liftedF(x,x)
res0: Option[Int] = Some(1764)

scala> liftedF(x,y)
res2: Option[Int] = None

我们甚至可以概括这一点……请遮住你的眼睛:

 def lift2[A, B, C](f: (A, B) => C): (Option[A], Option[B]) => Option[C] = (a: Option[A], b: Option[B]) =>
    for (x <- a; y <- b) yield f(x, y)
于 2013-04-18T08:18:12.047 回答