Haskell 中有分割字符串的标准方法吗?
lines
和 words
在空格或换行符上分割效果很好,但是肯定有一种标准的方法来在逗号上分割吗?
我在 Hoogle 上找不到它。
具体来说,我正在寻找 split ",""my,comma,separated,list"
返回 ["my","comma","separated"的内容,“列表”]
。
最佳答案
请记住,您可以查找 Prelude 函数的定义!
http://www.haskell.org/onlinereport/standard-prelude.html
看那里,单词
的定义是,
words :: String -> [String]
words s = case dropWhile Char.isSpace s of
"" -> []
s' -> w : words s''
where (w, s'') = break Char.isSpace s'
因此,将其更改为采用谓词的函数:
wordsWhen :: (Char -> Bool) -> String -> [String]
wordsWhen p s = case dropWhile p s of
"" -> []
s' -> w : wordsWhen p s''
where (w, s'') = break p s'
然后用你想要的任何谓词来调用它!
main = print $ wordsWhen (==',') "break,this,string,at,commas"
关于string - 如何在 Haskell 中分割字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4978578/