2.7.2. Anonymous funs

Although alias funs are useful, the real power comes with the syntax for anonymous funs, also known as lambda expressions. Like the funs in the previous section, they start with the fun keyword; and like a case expression, they end with the end keyword. Between those keywords, they look like one or more function clauses without any function names. For example, here is the simplest possible anonymous fun. It takes no arguments and always returns zero:

fun () -> 0 end

Here, on the other hand, is a more complicated one—it does exactly the same thing as the area function from section 2.5.4, but it has no name:

fun ({circle, Radius}) -> Radius * Radius * math:pi(); ({square, Side}) -> Side * Side; ({rectangle, Height, Width}) ...

Get Erlang and OTP in Action now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.