How to split a string in Haskell?

ID : 20363

viewed : 16

Tags : stringhaskellstring

Top 5 Answer for How to split a string in Haskell?

vote vote

93

Remember that you can look up the definition of Prelude functions!

http://www.haskell.org/onlinereport/standard-prelude.html

Looking there, the definition of words is,

words   :: String -> [String] words s =  case dropWhile Char.isSpace s of                       "" -> []                       s' -> w : words s''                             where (w, s'') = break Char.isSpace s' 

So, change it for a function that takes a predicate:

wordsWhen     :: (Char -> Bool) -> String -> [String] wordsWhen p s =  case dropWhile p s of                       "" -> []                       s' -> w : wordsWhen p s''                             where (w, s'') = break p s' 

Then call it with whatever predicate you want!

main = print $ wordsWhen (==',') "break,this,string,at,commas" 
vote vote

88

There is a package for this called split.

cabal install split 

Use it like this:

ghci> import Data.List.Split ghci> splitOn "," "my,comma,separated,list" ["my","comma","separated","list"] 

It comes with a lot of other functions for splitting on matching delimiters or having several delimiters.

vote vote

72

If you use Data.Text, there is splitOn:

http://hackage.haskell.org/packages/archive/text/0.11.2.0/doc/html/Data-Text.html#v:splitOn

This is built in the Haskell Platform.

So for instance:

import qualified Data.Text as T main = print $ T.splitOn (T.pack " ") (T.pack "this is a test") 

or:

{-# LANGUAGE OverloadedStrings #-}  import qualified Data.Text as T main = print $ T.splitOn " " "this is a test" 
vote vote

62

In the module Text.Regex (part of the Haskell Platform), there is a function:

splitRegex :: Regex -> String -> [String] 

which splits a string based on a regular expression. The API can be found at Hackage.

vote vote

58

Use Data.List.Split, which uses split:

[me@localhost]$ ghci Prelude> import Data.List.Split Prelude Data.List.Split> let l = splitOn "," "1,2,3,4" Prelude Data.List.Split> :t l l :: [[Char]] Prelude Data.List.Split> l ["1","2","3","4"] Prelude Data.List.Split> let { convert :: [String] -> [Integer]; convert = map read } Prelude Data.List.Split> let l2 = convert l Prelude Data.List.Split> :t l2 l2 :: [Integer] Prelude Data.List.Split> l2 [1,2,3,4] 

Top 3 video Explaining How to split a string in Haskell?

Related QUESTION?