What atom name to represent a null value

Tim Fletcher <>
Fri Feb 26 08:40:53 CET 2010


> It is defined in somewhere? Some documentation?
>
> Or just in common sense?

I suspect it is a practical application of the theoretical notion of
undefined in functional programming (and mathematics). For example,
here's a little function:

  foo(1) -> 2;
  foo(2) -> 3;
  foo(3) -> 1.

This function is only defined for the values 1, 2, and 3. It is
undefined for any other value. You can use the theoretical notion of
undefined when doing certain transformations on this function and so
on.

On a practical level, calling this function with any other value will
throw an error, which isn't always helpful. What if you wanted to pass
in any integer? In Erlang you can write this:

  foo(1) -> 2;
  foo(2) -> 3;
  foo(3) -> 1.
  foo(_) -> undefined.

You can then call foo(4) and have it actually return a value, which
means you can then write things like foo(X) =:= 1 without it throwing
a badmatch error.


Sometimes you may want to distinguish between values that aren't
defined, and values that do exist but are null; in this case you can
use undefined in combination with null/nil/none/nothing, as long as
your values aren't atoms.

If your values can be atoms then you'll probably need to use tagged
tuples, something like this:

  > datastore:lookup(foo).
  undefined % key/value is not defined

  > datastore:lookup(bar).
  none % key exists, value is "null"

  > datastore:lookup(baz).
  {ok, undefined} % key exists, value is undefined

The important thing is to be able to distinguish between the different
cases.


Hope that helps.

Tim


More information about the erlang-questions mailing list