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

Anthony Ramine n.oxyde@REDACTED
Mon Mar 3 02:11:32 CET 2014


The point is to crash if any of the inputs are not of the right type.

If Fun is not an unary function and List isn’t empty, the function will crash when trying to call Fun, so there is no is_function/2 guard in the first clause.

-- 
Anthony Ramine

Le 21 févr. 2014 à 08:20, Sergey Yelin <elinsn@REDACTED> a écrit :

> 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.
> 
> 
> 
> _______________________________________________
> erlang-bugs mailing list
> erlang-bugs@REDACTED
> http://erlang.org/mailman/listinfo/erlang-bugs




More information about the erlang-bugs mailing list