lists:splitwith/2 and similar functions

James Hague james@REDACTED
Fri Nov 1 05:09:14 CET 2002


I've found myself often writing code that's similar to 
lists:splitwith/2:  given a list, return a tuple of {A,B}, where "A" 
is a prefix of the list where all elements meet some critera, and "B" 
is the rest of the list.  splitwith works in the usual way, building 
list "A" backward, then calling lists:reverse at the end to flip it 
around.

Another approach is to count the number of elements that would be in 
"A" without doing any list building.  Once the count is known, it's 
easy to build "A" in a second pass.  Call the second function 
"split":  split(2, "12ab") returns {"12", "ab"}.  I argue that this 
method is cleaner than building a list and reversing it.  But the 
nice part is that "split" could be written as a BIF.  It could 
execute in constant stack space *and* avoid building a list that gets 
thrown away after a reversed copy of it is made.

Ideally, splitwith could be written as:

splitwith(Pred, L) -> lists:split(lists:count(Pred, L), L).

and certainly lists:count and lists:split would be useful elsewhere.



More information about the erlang-questions mailing list