[erlang-questions] Additions to lists module

Zvi exta7@REDACTED
Wed Nov 26 17:18:43 CET 2008


Serge,

I would call it "find_first" instead of "pos", with additional "find_last"
and "find".

find_first(L, E) -> pos(L, E).
find_last(L, E) -> find_first(lists:reverse(L), E).

% return indices of all list elements equal to E
find(L), E ->
       find(L,E,1,[]).
find([], _, _, A) -> lists:reverse(A);
find([E|T], E, I, A) -> find(T, E, I+1, [I|A]);
find([_|T], E, I, A) -> find(T, E, I+1, A).


Zvi


Serge Aleynikov-2 wrote:
> 
> I'd like to propose addition of these two functions to the lists module. 
>   Very often I find the need for this functionality and feel that it 
> belongs to the standard library.
> 
> Serge
> 
> 
> 
> %% @spec (List::list(), Ele) -> integer()
> %% @doc Returns the position of `Ele' in the `List'. 0 is returned
> %%      when `Ele' is not found.
> %% @end
> pos(List, Ele) ->
>      pos(List, Ele, 1).
> pos([Ele | Tail], Ele, Pos) ->
>      Pos;
> pos([_ | Tail], Ele, Pos) ->
>      pos(Tail, Ele, Pos+1);
> pos([], _Ele, _) ->
>      0.
> 
> %% @spec (Pred, Acc, List::list()) -> Acc1
> %%          Pred = (Ele, Acc) -> Acc1
> %% @doc A combination of foldl/3 and takewhile/2. Accumulate the result
> %%      while the predicate function returns true.
> %% @end
> foldlwhile(Pred, Acc0, [H|T]) ->
>      case Pred(H, Acc0) of
>      {true, Acc} ->
>          foldwhile(Fun, Acc, T);
>      {false, Acc} ->
>          Acc;
>      end;
> foldlwhile(_Pred, Acc, []) ->
>      Acc.
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
> 
> 

-- 
View this message in context: http://www.nabble.com/Additions-to-lists-module-tp20700771p20704131.html
Sent from the Erlang Questions mailing list archive at Nabble.com.




More information about the erlang-questions mailing list