How to split a string in Haskell?

后端 未结 13 1610
日久生厌
日久生厌 2020-11-28 03:08

Is there a standard way to split a string in Haskell?

lines and words work great from splitting on a space or newline, but surely there is

13条回答
  •  臣服心动
    2020-11-28 03:59

    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"
    

提交回复
热议问题