[erlang-questions] lists:takewhile and lists:splitwith

Richard O'Keefe ok@REDACTED
Thu Feb 3 22:29:56 CET 2011


On 3/02/2011, at 10:56 PM, maruthavanan s wrote:

> 
> Hi,
> 
> The document says lists:takewhile(Pred,List) would return tuple of lists which would split the List when Pred returns true.

No it doesn't.  This is what the documentation says:

    takewhile(Pred, List1) -> List2

        Types:

            Pred = fun(Elem) -> bool()
            Elem = term()
            List1 = List2 = [term()]

        Takes elements Elem from List1 while Pred(Elem) returns true,
        that is, the function returns the longest prefix of the list
        for which all elements satisfy the predicate.


> 
> I tried the below.
> 
> lists:takewhile(fun(A)-> A==3 end,[1,2,3,4,5]).
> 
> it gives me an empty result..

And indeed the longest prefix of [1,2,3,4,5] such that all elements
are the number 3 really and truly is [].

> What should I do to  get {[1,2],[3,4,5]}

Write your own function.

What you want is

	Pred, [X1,...,Xk] => {[Y1,...,Ym],[Z1,...,Zn]}
	such that [Y1,...,Ym]++[Z1,...,Zn] is [X1,...,Xk]
             and all(Pred, [Y1,...,Ym]
             and n = 0 or not Pred(Z1).

split_at_first(Pred, List) ->
    split_at_first_loop(Pred, List, []).

split_at_first_loop(Pred, [], Reversed_Prefix) ->
    {lists:reverse(Reversed_Prefix), []};
split_at_first_loop(Pred, [X|Xs], Reversed_Prefix) ->
    case Pred(X)
      of true  -> {lists:reverse(Reversed_Prefix), [X|Xs]}
       ; false -> split_at_first_loop(Pred, Xs, [X|Reversed_Prefix])
    end.

You should probably ask yourself whether [Ym,...,Y1] will do just as
well as [Y1,...,Ym].




More information about the erlang-questions mailing list