DEV Community

Discussion on: How I (Finally) Built an App in Elm

Collapse
 
heikodudzus profile image
Heiko Dudzus • Edited

I agree, just returning a value in a Maybe and then getting the value out of the Maybe functor by pattern matching via 'case' is clunky. That's not what Maybe is invented for.

The Maybe type can, in fact, reduce clunkiness of the code. But only if you are using it as (Applicative) Functor or Monad to propagate the failure transparently through some other part of your code.

As an example, in one of my projects, I have a function 'intersection' that computes a point of intersection for two given line segments. Two line segments can have an intersection, but need not to have. So using Maybe seems good.

intersection :: LineSeg -> LineSeg -> Maybe Point

In the further code, there is a function 'triangle' that takes three Points and returns the corresponding Triangle:

triangle :: Point -> Point -> Point -> Triangle

As you can guess, the program will at some point compute the Triangle built by three line segments. And this is where Maybe begins to shine:

triangleABC = triangle <$> intersection a b <*> intersection a c <*> intersection b c

You see what happend here: The triangle function was written for Points that really exist. But I have applied it to intersection points that maybe exist but maybe not! I could do so, because I used Maybe as Applicative Functor.

Of course, if any of the three intersections doesn't exist, triangleABC is Nothing. If they all three exist, triangle ABC is in a Just. Maybe reduces the need for clunky case analysis, but only if you really use it as Applicative Functor or Monad, that helps you to propagate Maybe data through your code. Otherwise it makes the code clunky, yes.

You can build bigger structures of 'Maybe Triangle's. The point is: You can write your code without having to think about (and deal with) the annyoing failures, you can concentrate on the cases where all is good, like I have done with my function 'triangle'.

I wanted to share some real code examples regarding Maybe, but it is better explained in full length here: learnyouahaskell.com/functors-appl... and here: learnyouahaskell.com/a-fistful-of-...

Edit: <$> seems to be <~ in Elm and <*> is ~
See the example in elm-lang.org/blog/announce/0.7