[Haskell-cafe] Maybe a, The Rationale
sebastian.sylvan at gmail.com
Sat May 10 21:03:56 EDT 2008
On Sat, May 10, 2008 at 11:36 PM, PR Stanley <prstanley at ntlworld.com> wrote:
> Hi folks
> data Maybe a = Nothing | Just a
> What is the underlying rationale for the Maybe data type? is it the
> safe style of programming it encourages/
> Something tells me this is going to start a lengthy discussion. :-)
> Cheers, Paul
Sometimes you want to express things that can either be a value, or nothing.
In some languages all or most "values" (using that term loosely) can be
"nullable". E.g. in C# any reference can be nullable, so you can just return
null to signify "no value" (e.g. when looking someting up in a dictionary).
The problem with this is that every single dereference can no potentially
cause a runtime error, which pushes a whole lot of problems to the runtime,
when they really could be statically eliminated at compile time. Most
functions, after all, really do need all their parameters to "exist" and
aren't defined for null, and they really do return a result and never null,
so it's useful to know for sure that a "Map Int String" really is a map, and
not "null", while you still have the ability to deal with "optional" values
in the tiny minority of cases that need it.
Also, since it's impossible to actualy use a value without inspecting the
constructors of Maybe, you avoid even more runtime errors (unless you use
things like "fromJust"). IME "nullable by default" is one of the biggest
sources of runtime crashes in high level OOP languages like C#, which is a
shame because it really isn't that difficult to statically eliminate the
vast majority of them, especially when you're sort of hand-waving the
semantics of your language anyway and don't require it to be super
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe