[erlang-questions] To name a function

Ryan Zezeski rzezeski@REDACTED
Wed Dec 15 17:54:17 CET 2010


On Wed, Dec 15, 2010 at 11:06 AM, Attila Rajmund Nohl <
attila.r.nohl@REDACTED> wrote:

> Hello!
>
> I've found at least places in my code where I'd need a function which
> decides if all, some or none members of a list have a particular
> property (the list always has at least one element). How to name this
> function? The code is something like this:
>
> f(_F, []) ->
>  erlang:error({badarg, []});
>
> f(F, L) ->
>  {Has, Not} =
>    lists:foldr(
>      fun(E, {H, N}) ->
>        case f(E) of
>          true -> {H+1, N};
>          false -> {H, N+1}
>        end
>      end, {0,0}, L),
>  case {Has, Not} of
>    {0, _} -> none;
>    {_, 0} -> all;
>    _ -> some
>  end.
>
>
Well, I wouldn't give it any style points but I came up with all_some_none.
 Also, instead of using fold you could make use of lists:all/2 and
lists:filter/2.

%% BEGIN CODE
-module(funs).

-compile(export_all).

all_some_none(F, L) when length(L) > 0 ->
    case lists:all(F, L) of
        true ->
            all;
        false ->
            case lists:filter(F, L) of
                [] ->
                    none;
                _ ->
                    some
            end
    end.

even(N) ->
    N rem 2 =:= 0.

one(1) ->
    true;
one(_) ->
    false.

odd(N) ->
    N rem 2 =:= 1.
%%END CODE

1> c(funs).
{ok,funs}
2> L = [1,1,1,1].
[1,1,1,1]
3> funs:all_some_none(fun funs:even/1, L).
none
4> funs:all_some_none(fun funs:odd/1, L).
all
5> funs:all_some_none(fun funs:one/1, L).
all
6> L2 = [1,2,3,4].
[1,2,3,4]
7> funs:all_some_none(fun funs:even/1, L2).
some
8> funs:all_some_none(fun funs:odd/1, L2).
some
9> funs:all_some_none(fun funs:one/1, L2).
some


-Ryan


More information about the erlang-questions mailing list