[erlang-questions] Re: What atom name to represent a null value

Robert Virding <>
Fri Feb 26 10:43:01 CET 2010


On 26 February 2010 08:40, Tim Fletcher <> wrote:
>> 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.

The important thing here when deciding between these two cases is what
it means in your application if foo/1 is called with a value which is
not 1, 2 or 3.

If it is an error, a value which should never occur, a bug, then you
should definitely not add an extra clause which catches and returns a
"helpful" value. Doing this will force you to check error returns
through the rest of code to handle this which is definitely something
you wish to avoid.

If, on the other hand, this is not an error but just the default case
where you can return something sensible then adding the extra clause
makes sense.

As an example of the difference: dict:find/2 returns (the atom)
'error' if a key is found, while dict:fetch/2 throws an error if the
key is not found as it is defined to assume the key does exist.

Robert


More information about the erlang-questions mailing list