[erlang-questions] Funs

Jeremy Ong jeremy@REDACTED
Mon Nov 26 09:25:50 CET 2012

Anonymous functions or lambdas are a basic building box in any functional
programmer's toolbox. Examples of functions that take other anonymous
functions in the standard library are lists:map, lists:foldl, lists:filter,
and their analogs in the orddict library, sets library, etc. Of course, any
of those parameters can be named functions as well but if the function is
simple enough, an anonymous function is preferred for brevity (example,
lists:map(fun(Elem) -> Elem * 2 end, List) doubles the value of all
elements in List).

You can also accept a function as a parameter for any of your functions
too. For example:

every_other(Fun, List) ->
  {_, Res} = lists:foldl(fun(Elem, {Idx, Acc}) -> case Idx rem 2 of 0 ->
{Idx + 1, Acc ++ [Elem]}; 1 -> {Idx + 1, Acc ++ [Fun(Elem)]} end, List),

This returns a list with Fun applied to every other element.

On Mon, Nov 26, 2012 at 12:09 AM, Lucky Khoza <mrkhoza@REDACTED> wrote:

> Morning Erlang Developers,
> I would like to ask about: when do we use funs or anonymous functions in
> Erlang?, I know what it is, but I can't really figure out when to use it
> and I saw an example of it being used with Mnesia transactions.
> May someone help in this regard please.
> Kindest Regards
> Lucky Khoza
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20121126/8f5d42a6/attachment.htm>

More information about the erlang-questions mailing list