Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Haskell do-notation or F# Computation Expressions in Scala?

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.

like image 700
skyde Avatar asked Sep 20 '11 03:09

skyde


1 Answers

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.

like image 181
Kevin Wright Avatar answered Sep 27 '22 15:09

Kevin Wright