[erlang-bugs] Strange lists:foreach/2 declaration

Sergey Yelin <>
Fri Feb 21 08:20:31 CET 2014


Hello,

just found confusing behaviour for lists:foreach/2:

1> lists:foreach(xxx,[1,2,3]).
** exception error: bad function xxx
     in function  lists:foreach/2 (lists.erl, line 1323)
2> lists:foreach(xxx,[]).
** exception error: no function clause matching lists:foreach(xxx,[]) (lists.erl, line 1322)

so it returns two different errors for wrong function and it depends on whether list is empty or not.
Here is the snippet from lists.erl:

-spec foreach(Fun, List) -> ok when
      Fun :: fun((Elem :: T) -> term()),
      List :: [T],
      T :: term().

foreach(F, [Hd|Tail]) ->
     F(Hd),
     foreach(F, Tail);
foreach(F, []) when is_function(F, 1) -> ok.

So my question is it known bug (or feature)? Why there is no check for function when list is not empty?
May be following is better:

foreach(F, [Hd|Tail]) when is_function(F, 1) ->
     F(Hd),
     foreach(F, Tail);
foreach(F, [])  -> ok.

because actually F will be never call when list is empty?

---
Best regards,
Sergey Yelin.





More information about the erlang-bugs mailing list