[erlang-questions] lists:mapfind?

Richard A. O'Keefe ok@REDACTED
Mon Aug 21 01:22:10 CEST 2017



On 19/08/17 1:04 AM, zxq9 wrote:
> Good point.
>
> What are the cases not covered by the lists module?
> filter/2, partition/2, matching/guarded list comprehensions, etc?

We have all(Pred, List)
         any(Pred, List)
     but one(Pred, List) is missing.

%   one(Pred, List) is true when List has exactly one element X
%   such that Pred(X) is true.  Yes, this is useful.

one(Pred, [X|Xs]) ->
     case Pred(X)
       of true  -> not(any(Pred, Xs))
        ; false -> one(Pred, Xs)
     end;
one(_, []) ->
     false.


%   first(Pred, List) returns {ok,Value} when Value is the
%   first element of List such that Pred(Value), or error
%   if there is no such value.

first(Pred, [X|Xs]) ->
     case Pred(X)
       of true  -> {ok,X}
        ; false -> first(Pred, Xs)
     end;
first(_, []) ->
     error.

%   last(Pred, List) returns {ok,Value} when Value is the
%   last element of List such that Pred(Value), or error
%   if there is no such value.

last(Pred, [X|Xs]) ->
     case Pred(X)
       of true  -> last_aux(Pred, Xs, X)
        ; false -> last(Pred, Xs)
     end;
last(_, []) ->
     error.

last_aux(Pred, [X|Xs], Y) ->
     case Pred(X)
       of true  -> last_aux(Pred, Xs, X)
        ; false -> last_aux(Pred, Xs, Y)
     end;
last_aux(_, _, Y) ->
     {ok, Y}.


%  foldl1(Fun, List) is a relative of foldl/3 used when
%  the function has no (representable) left identity,
%  such as max and min.  It is an error if List is empty.

foldl1(Fun, [X|Xs]) ->
     foldl(Fun, X, Xs).

foldr1 is also missing.

The whole scan{l,r}{,1} family are missing.

As mentioned several years ago, unfold/2 is missing.

unfold(Fun, State) ->
     case Fun(State)
       of {Head,State1} -> [Head | unfold(Fun, State1)]
        ; []            -> []
     end.

takewhile and dropwhile are there, and drop is there
under the name nthtail, but take is not there.

uniq(List) -> List'
uniq(Eql, List) -> List'
    returns a subsequence of List with *adjacent*
    duplicates dropped,  Whenever there is a run
    ...x1,x2,...,xn such that Eql(xk_1, xk) for
    2<=k<=n, x1 is included in the result and
    x2...xn are not.  The default equality function
    is exact equality.  O(length(List)).

nub(List) -> List'
nub(Eql, List) -> List'
    returns a subsequence of List with duplicates
    dropped.  Whenever there is a pair ...xi...xj...
    such that Eql(xi, xj), xj is excluded from the
    result.  The default equality function is
    exact equality.  O(length(List)**2).

group(List) -> List_Of_Lists
group(Eql, List) -> List_Of_Lists
    returns a list of lists whose concatenation
    is the original List.  If [...xi...xj...] is
    an element of the result, Eql(xi, xj).  The
    Eql function should be transitive but need not
    be an equivalence; the default is exact equality.
    O(length(List)).




More information about the erlang-questions mailing list