Scala申请人?

时间:2014-09-19 02:11:46

标签: scala applicative

在Scala中,如何将Option[A]附加到Option[A]

含义:

Some("foo") ??? Some("bar") == Some("foobar")

在Haskell中,我使用了一个应用程序:

ghci>import Control.Applicative
ghci> (++) <$> (Just "foo") <*> (Just "bar")
Just "foobar"

Scala的标准Typesafe库中是否有Applicatives

3 个答案:

答案 0 :(得分:3)

使用scalaz,你可以这样做:

  import scalaz.syntax.applicative._
  import scalaz.std.option._

  val l: Option[String] = Some("foo")
  val r: Option[String] = Some("bar")
  val result = ^(l, r)(_ + _)
  println(result) // Some("foobar")

答案 1 :(得分:2)

应用程序不在标准库中,但您可以在Haskell中使用像monad这样的for-understanding:

for {
  l <- Some("foo")
  r <- Some("bar")
} yield (l + r)

(或者用flatMap重写它)。否则,请使用scalaz,就像Eugene的回答一样。

答案 2 :(得分:0)

如果您只想实现这种特定语法,可以将隐式类与monad for-understand理结合起来:

implicit class RichOption(a: Option[String]) {
  def ???(b: Option[String]) = for (sa <- a; sb <- b) yield sa+sb
}

scala> Some("foo") ??? Some("bar") == Some("foobar")
res4: Boolean = true
相关问题