3 ms·
I think something was missed, and maybe I missed it. It looks to me like this: var a = getData(); if (a != null) { var b = getMoreData(a);
by andrewprock 9y ago
I think something was missed, and maybe I missed it. It looks to me like this:
var a = getData();
if (a != null) {
var b = getMoreData(a);
if (b != null) {
var c = getMoreData(b);
if (c != null) {
var d = getEvenMoreData(a, c)
if (d != null) {
print(d);
}
}
}
}
will only print on non-null, whereas this:
do
a <- getData
b <- getMoreData a
c <- getMoreData b
d <- getEvenMoreData a c
print d
will always print something.
- foldr 9y ago>will always print something. Not necessarily. It depends on which monad is being used here (the article doesn't specify). If you replace the 'print' with 'return' to simplify things, then this could be an expression in the Maybe monad, which would return either (Just d) or Nothing. The article is lying a bit by suggesting that it's trivial to layer short-circuit-on-error behavior on top of the IO monad. It's possible for sure, but some relatively subtle issues can arise (in Haskell at least).
- andrewprock 9y agoThis is what I always hated with C++, and to a lesser extent Java. The code that you cannot see makes it very difficult to understand the code when reading the source. If the only person that can truly understand the code is the author, that is an anti-pattern. The for loops and if statements were never a problem, it was the default constructors, overloaded operators, and the like that always caused confusion on my teams.
- foldr 9y agoIn simple cases you'd be able to see the concrete type if this were real Haskell code, so you'd know which monad instance was the relevant one. Your complaint does apply to some uses of the monad transformer library, however.
- jhomedall 9y agoIt won't. If any of the functions on the right-hand side of the '<-' return Nothing, then the later lines do nothing. Think of the '<-' operator as a 'flatMap' call for Optionals in Java, if you are more familiar with that. This particular syntax for chaining together monads is called 'do notation', and is just syntax sugar for calling the bind function (flatMap in Java) manually.
- vilhelm_s 9y agoThe two blocks of code are exactly equivalent, the "if != null" logic is moved into the <-.
- dullgiulio 9y agoAnd the first snipped is purposely badly written. One can use early returns to make code flat just like the monadic example.
- mclehman 9y agoSure, you can flatten that example, but I'd still be interested in losing the explicit and repetitive null checks.
- andrewprock 9y agoIn the old days, we used #define macros to do that.