41 ms·
Maybe is a monad, which means Maybe computations can be chained together with `>>=` (or using `do` notation) without checking for `Nothing`. You can easily prod
by tmhedberg 14y ago
Maybe is a monad, which means Maybe computations can be chained together with `>>=` (or using `do` notation) without checking for `Nothing`. You can easily produce a large composition of potentially-failing computations while completely ignoring the possibility of failure.
The case analysis you give as an example is only required at the point when you want to extract the final result into a different monadic context, and even then you would typically use the `maybe` or `fromMaybe` functions to make it more concise.
Only a novice Haskell user would write:
case comp1 of
Nothing -> handleFailure
Just r1 ->
case comp2 r1 of
Nothing -> handleFailure
Just r2 ->
case comp3 r2 of
Nothing -> handleFailure
Just r2 -> handleResult r3
which is indeed, just as bad as explicit null checking in C or Java, with runaway indentation to boot. But anyone who understands Haskell's rich abstractions would instead write:
maybe handleFailure handleResult $ comp1 >>= comp2 >>= comp3
The fact that you can't forget the "null check" without the compiler telling you about it is a nice convenience afforded by the strong type system, but it's far from the only benefit.
- irahul 14y ago> Maybe is a monad, which means Maybe computations can be chained together with `>>=` (or using `do` notation) without checking for `Nothing`. You can easily produce a large composition of potentially-failing computations while completely ignoring the possibility of failure. Like val = foo.bar.blah.boo rescue nil Or try { val = foo.bar().blah().boo() } catch(NullPointerException ex) { } Or try: val = foo.bar().blah().boo() except AttributeError: pass Yes, I know Maybe is a monad, but that doesn't make a difference to me. A series of computation where a step depends on the results of the previous step and the previous step can return null is hardly an issue in any language. > The case analysis you give as an example is only required at the point when you want to extract the final result into a different monadic context, and even then you would typically use the `maybe` or `fromMaybe` functions to make it more concise. The case analysis I give is an example where either there is a value or null and I need the value. I don't really care how Haskell defines monadic context.