« QuickCheck rocks my socks » Abstraction, intuition, and the "monad tutorial fallacy"

Data.List.Split

Posted on December 21, 2008
Tagged , ,

Have you ever had a string like this “abc;def;ghijk;lm” and wanted to turn it into a list of strings, like this? [“abc”, “def”, “ghijk”, “lm”] Of course, you could always use a parsing library, or a regular expression library, but sometimes you just want something a little more lightweight. Perl and Ruby both have library functions called “split” to do just this. Haskell’s standard libraries, on the other hand, have no such function, much to the consternation of many a newbie and experienced Haskeller alike. There have been many proposals to add such a thing to the standard Data.List module in the past, but nothing ever came of it, primarily because there are many slightly different ways to split a list, and no one could ever agree on the One True Splitting Interface.

I decided we’ve been Doing It Wrong. Instead of bickering about the one true interface and going through the stringent library proposals process, let’s just get some useful code together and release it on Hackage. (Of course there are advantages to inclusion in the standard libraries — but that can come later.) So I solicited contributions on a wiki page, took some of the ideas, bits of code, and some ideas of my own, and created Data.List.Split.

Instead of talking about it more, I’ll just show some examples:

Data.List.Split> splitOn “;” “abc;def;ghijk;lm” [“abc”,“def”,“ghijk”,“lm”] Data.List.Split> splitWhen (<0) [1,4,-8,4,-3,-2,9] [[1,4],[4],[],[9]] Data.List.Split> split (startsWith “app”) “applyappicativeapplaudapproachapple” [“apply”,“appicative”,“applaud”,“approach”,“apple”] Data.List.Split> split (dropDelims $ oneOf “:;”) “::abc;:;;fg:h;;ij;” [““,”“,”abc”,““,”“,”“,”fg”,“h”,““,”ij”,“”] *Data.List.Split> split (condense . dropInitBlank $ oneOf “:;”) “::abc;:;;fg:h;;ij;” [“::”,“abc”,“;:;;”,“fg”,“:”,“h”,“;;”,“ij”,“;”,“”]

Detailed documentation can be found in the package itself. Install it from Hackage: cabal install split

You can also check out the darcs repo. Comments, suggestions, and patches welcome!