[Haskell-beginners] Maybe and Just

martin martin.drautzburg at web.de
Thu Mar 26 21:04:47 UTC 2015


Am 03/26/2015 um 11:06 AM schrieb Shishir Srivastava:
> Hi, 
> 
> 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. 
> 
> 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.

My intuition goes like that:

"Maybe" is like "nullable" (which doesn't really exist, but you sure can imagine what it means). In many programming
languages a variable of any type can contain "null", i.e. every type is nullable. This means that any function accepting
one of these types as a parameter must be prepared to see a null. You end up with many checks like

	if (x==null) {return null;}

Not so in haskell. An Int is really an Int and Ints cannot be null. Functions accepting Ints don't have to check for null.

But you can beef up any datatype to be nullable. You can create a TYPE "nullable Int" which would be called "Maybe Int"
in Haskell. Just like "nullable" alone, Maybe itself is not a type, but an up-beefer of another type. There are no
values of type Maybe, but only of Maybe Int, Maybe String etc. In that respect maybe is like "List". There are no values
of type "List", but only of List of Int, List of String. List is an up-beefer too (written as [] in Haskell)

Obviously there needs to be a distinct VALUE for "null". In Haskell this value is called "Nothing".

For the non-null VALUES you could think about  writing them verbatim, like "42". But from just looking at 42, you
couldn't tell what type it is. It could be an Int or a Maybe Int. This problem is somewhat akin to writing 42.0 when you
want to make sure it is a float (in imperative languages), or 42L to indicate it is a long.

So in the same vein, you distinguish an Int (42) from a Maybe Int (Just 42). Just 42 is a value of type Maybe Int, which
just (sic!) happens not to be null, but it is still not a plain Int, but a Maybe Int. Like 42.0 is a float which happens
not to have any digits after the decimal point but also is not a plain Int but a float.




More information about the Beginners mailing list