[erlang-questions] Self-referencing anonymous functions?

Richard Carlsson <>
Thu Apr 2 20:48:06 CEST 2009


Thomas Allen wrote:
> I'm just getting going with Erlang (using Armstrong's book) and I ran
> into anonymous functions. I tried translating the shop:cost and
> shop:total functions, but I cannot translate the latter because it
> refers to itself. How would I rewrite this to not throw errors?
> 
> Total = fun ([{What, N}|T]) ->
>         Cost(What) * N + Total(T); % Clearly, "Total" won't fly here
>     ([]) -> 0
> end.

You have to make it a parameter of the function, and then
keep passing it the reference to itself, like this:

  Total = fun ([{What, N}|T], ThisFunction) ->
            Cost(What) * N + ThisFunction(T, ThisFunction);
              ([], ThisFunction) -> 0
          end,
  Sum = Total(SomeList, Total)

you can wrap the initial call in another fun, like this:

  MyTotal = fun (List) -> Total(List, Total) end,
  Sum = MyTotal(SomeList)

     /Richard



More information about the erlang-questions mailing list