As I understand it, Scala "for" syntax is extremely similar to Haskell's monadic "do" syntax. In Scala, "for" syntax is often used for List
s and Option
s. I'd like to use it with Either
s, but the necessary methods are not present in the default imports.
for {
foo <- Right(1)
bar <- Left("nope")
} yield (foo + bar)
// expected result: Left("nope")
// instead I get "error: value flatMap is not a member..."
Is this functionality available through some import?
There is a slight hitch:
for {
foo <- Right(1)
if foo > 3
} yield foo
// expected result: Left(???)
For a List, it would be List()
. For Option
, it would be None
. Do the Scala standard libraries provide a solution to this? (Or perhaps scalaz
?) How? Suppose I wanted to provide my own "monad instance" for Either, how could I do that?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…