[Haskell-cafe] Trapped by the Monads

Glynn Clements glynn at gclements.plus.com
Tue Sep 20 17:10:12 EDT 2005

Mark Carter wrote:

> > Could you briefly elaborate on what you mean by "hybrid variables"?
> According to Google, hybrid in genetics means "The offspring of 
> genetically dissimilar parents or stock, especially the offspring 
> produced by breeding plants or animals of different varieties, species, 
> or races." It's kind of like that - but for variables.
> The typical example in C is:
>  mem = malloc(1024)
> Malloc returns 0 to indicate that memory cannot be allocated, or a 
> memory address if it can. The variable mem is a so-called hybrid 
> variable; it crunches together 2 different concepts: a boolean value 
> (could I allocate memory?) and an address value (what is the address 
> where I can find my allocated memory).

Well in that case, Maybe provides the perfect example of how to
implement hybrid variables correctly.

The types "Ptr a" and "Maybe (Ptr a)" are distinct. If you try to pass
the latter to a function which expects the former, you'll get a
compile-time error. You first have to extract the underlying value,
which means that you need to match against (Just x). If the wrapped
value is Nothing, you'll get an exception. Furthermore, if you forget
to handle the Nothing case, you'll get a compile-time warning.

In C, there's no way to distinguish (using the type system) between a
possibly-null pointer and a non-null pointer. Using a pair of a
boolean and a pointer is the wrong approach because the pointer is
meaningless if the boolean is false, but the type system won't prevent
you from using the value of the pointer in that case.

A more general example is structures where certain fields are only
valid in certain circumstances (e.g. depending upon the "type" field). 
Haskell-style sum types, (of which Maybe is an example) are a much
better solution, as the the fields only exist when they are

Glynn Clements <glynn at gclements.plus.com>

More information about the Haskell-Cafe mailing list