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.
for
comprehensions is exactly right. They desugar tomap
andflatMap
behind the scenes, which is exactly how Haskelldo
notation works (except those methods are calledfmap
and>>=
in Haskell). – Georgeannageorgeannefmap
is actually not used in Haskell desugaring ofdo
-notation, because there is noyield
statement which necessitates it (and also we can't be sure allMonad
s areFunctor
s, even though they should be)... instead of a keywordyield
you just use thereturn
function which, when called as the last statement in ado
block, amounts to anfmap
. – Georgeannageorgeannefor
is too strongly associated with looping; there's no way around it; extracting values fromOption
s reads quite awkward (especially to the untrained eye) using afor
-loop like syntax, and I'm still not comfortable with it after a few months, especially when somebody else looks at the code who might not be a Scala expert. – Chaineyloop
, ordo
/loop
, with nofor
in sight. So, I get and respect that one might feel this way, but the thing to do is get over it, in my opinion. – Breakerfor
for looping,for
should not be assumed to be associated with looping" – Chaineyfor
for looping,for
should be assumed to be associated with looping", so you don't have a leg to stand on. Regardless, that's not what I said. What I said is that this association is a result of limited exposure to programming languages -- being forced to drop unreasonable assumptions (loop
is reasonably associated with loops, butfor
?) is a result of expanding your horizons, and Scala is as good a start as any for that. – Breakerfor
for constructs other than looping? – Chaineyloop
for them, and that people learning more than a few closely related languages should be prepared to drop the conventions learned from those languages. – Breakerfor
associates with looping, and for a good reason. Yes, it's possible to "get over it", but that doesn't change the point really. – Chainey