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


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

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


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


If you use Data.Text, there is 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") 


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


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


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?