F# Computation Expressions allow to hide the complexity of monadic syntax behind a thick layer of syntactic sugar. Is there something similar available in Scala?
I think it's for comprehensions ...
Example:
val f = for {
a <- Future(10 / 2) // 10 / 2 = 5
b <- Future(a + 1) // 5 + 1 = 6
c <- Future(a - 1) // 5 - 1 = 4
} yield b * c // 6 * 4 = 24
val result = f.get
But it doesn't really feel right. Is there a better syntax?
for exemple in haskell you would have
main = do fromHandle <- getAndOpenFile "Copy from: " ReadMode toHandle <- getAndOpenFile "Copy to: " WriteMode contents <- hGetContents fromHandle hPutStr toHandle contents hClose toHandle putStr "Done."
this unlike scala doesn't look like a foreach loops. Scala syntax seem to have too strong coupling with List comprehension which is a distinct concept. Which prevent me from writing internal DSL (monad) that doesn't look strange.
The missing piece is probably the use of =
is scala's for-comprehensions:
val f = for {
a <- Future(10 / 2) // 10 / 2 = 5
b <- Future(a + 1) // 5 + 1 = 6
c <- Future(a - 1) // 5 - 1 = 4
d = b * c // 6 * 4 = 24
} yield d
val result = f.get
With judicious mixing of both <-
and =
, you should have all the flexibility you need.
似乎scala中没有这样的语法,我们需要使用编译器插件架构自己实现它。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.