I didn’t think this was possible, but as I was perusing some code (and consequently making a fork), I discovered there is syntax to support this. Check out these two examples.

Pattern Matching

1> P = fun(undefined) -> null; (X) -> X end.
#Fun<erl_eval.6.13229925>
2> P(undefined).
null
3> P(42). 
42

Guard Expressions

4> G = fun(X) when X==undefined -> null; (X) -> X end.
#Fun<erl_eval.6.13229925>
5> G(undefined).
null
6> G(42).
42

 

Advertisements