Haskell中的groupBy函数

时间:2015-03-10 02:10:12

标签: haskell

我知道Data.List模块带有预定义的函数groupBy,我想用它将一个字符串拆分成连续的元音和非元音的组。函数groupBy的格式如下:

groupBy :: (a -> a -> Bool) -> [a] -> [[a]]

如何使用此格式对字符串进行拆分? 感谢

1 个答案:

答案 0 :(得分:6)

喜欢这个

ghci> import Data.Char
ghci> import Data.List
ghci> groupBy (const isAlphaNum) "A bunch of words and numbers34"
["A"," bunch"," of"," words"," and"," numbers34"]

或者

ghci> groupBy (const isAlpha) "A bunch of words and numbers34"
["A"," bunch"," of"," words"," and"," numbers","3","4"]

编辑:由于没有迹象表明已找到扩展问题的解决方案,为了保持SO的标准,我将完成问题的答案:

import Data.List

isVowel :: Char -> Bool
isVowel c = c `elem` "aeiouy"

bothVowelConsonant :: Char -> Char -> Bool
bothVowelConsonant a b = all isVowel [a,b] || not (any isVowel [a,b])

splitByVowel :: String -> [String]
splitByVowel s = groupBy bothVowelConsonant s