[Haskell-beginners] Maybe and Just

Michael Alan Dorman mdorman at ironicdesign.com
Thu Mar 26 10:26:15 UTC 2015


Shishir Srivastava <shishir.srivastava at gmail.com> writes:
> After reading and re-reading the haskell tutorials I don't happen to
> see a very convincing or appealing reason for having these data
> types.

To be clear: Maybe is the data *type*.  Just and Nothing are its data
*constructors*.

> Can anyone please explain where Maybe and Just provide the sort of
> functionality that cannot be achieved in other languages which don't
> have these kind.

The functionality can be achieved in other languages, certainly.  The
question is whether the clarity and safety is also achieved.

When I see (as a totally contrived example):

  fopen :: Maybe FileHandle

I know that that function may not be able to return a FileHandle value
all the time.  The compiler will, in fact, nag me if I do not write the
code that calls it in such a way that it acknowledges that possibility.

When I see:

  FILE * fopen ( const char * filename, const char * mode );

It is not immediately clear whether that can fail.  Sure, we can make
that inference, based on what we know about filesystems, etc., but the
compiler is never going to complain if I ignore the possibility.

In my experience, programmers in many languages end up resorting to
convention to try and work around these sorts of ambiguities.  Large
projects have strategies for naming functions that try to pass along
information out of band, or languages have a pervasive culture of "lint"
tools that try to use heuristics to make up for what the type system
doesn't make simple.

That said, I know that doing Maybe sorts of things in languages that
don't have, say, pattern matching, or the idea of a "failure monad",
gets to be a drag very quickly---manually unwrapping things is at best
awkward, having to re-wrap them just to unwrap them again in a sequence
of computations quickly leads one to believe "it's just not worth
it"---or you resort to exception handling, which has its own challenges
to do well.

Mike.


More information about the Beginners mailing list