lists:partition/2
Luke Gorrie
luke@REDACTED
Wed Jan 17 14:53:13 CET 2001
Raimo Niskanen <raimo@REDACTED> writes:
> Hello,
>
> I am missing function in the module lists, one that using a predicate
> partitions a list into two; one with all elements for which the
> predicate was true, and one for the rest, while preserving the ordering
> of the elements.
Yes yes!
And here are a few other functions I've written lots of times:
%% For 'lists'
%% separate(X, L):
%% Separate the elements of the list L by placing X between them.
%% e.g.: lists:flatten(separate(", ", ["foo", "bar", "baz"]))
%% => "foo, bar, baz"
separate(X, []) -> [];
separate(X, [H]) -> [H];
separate(X, [H|T]) -> [H,X|separate(X, T)].
%% For 'lists'
%% first(Pred, List)
%% Find the first element of List satisfying Pred.
%% Returns: {value, Item} | false
first(Pred, []) ->
false;
first(Pred, [H|T]) ->
case Pred(H) of
true ->
{value, H};
false ->
first(Pred, T)
end.
%% For 'io_lib'
%% Very simple, but it's amazing how often
%% lists:flatten(io_lib:format(..)) makes me go over the 80-column
%% boundry :)
flatformat(Fmt, Args) ->
lists:flatten(io_lib:format(Fmt, Args)).
I know that you can do the 'first' with 'dropwhile' and so on, but I'd
still like to have these :-)
P.S. it's very nice that the latest erlang's lists:sort can take a
predicate!
Cheers,
Luke
More information about the erlang-questions
mailing list