[Haskell-cafe] Separate a string into a list of strings
donn at drizzle.com
Tue Jun 13 02:25:05 EDT 2006
Quoth Clifford Beshers <clifford.beshers at linspire.com>:
| Well, I couldn't resist the puzzle. Here are solutions using foldr and
| unfoldr. Don't know if they are cunning or not, but they were kind of fun.
| splitByElem1 e xs =
| foldr f [] xs
| where f a b = if a == e then  : b else (a : head b) : (tail b)
This does the right thing with trailing separators, which is not to be
taken for granted among Haskell split implementations. The splits I have
been seeing in this thread are conservative, so if the separator is ':',
then "::a" splits to ["", "", "a"]. Frequently however the implementation
fails to deal with the trailing separator, so "a:" is ["a"], where it
should be ["a", ""]. It's not something you run into right away.
In a liberal split, "a " should indeed be ["a"], but that's a different
matter. Neither of the two I've looked at seems to be shooting for a
liberal "words" white space split.
More information about the Haskell-Cafe