String Haskell按第一个空格分解单词
注意这与使用words函数不同 我想从中转换:String Haskell按第一个空格分解单词,string,haskell,String,Haskell,注意这与使用words函数不同 我想从中转换: "The quick brown fox jumped over the lazy dogs." 为此: ["The"," quick"," brown"," fox"," jumped"," over"," the"," lazy"," dogs."] 注意每个单词后第一个空格上的换行符 我能想到的最好的办法是: parts "" = [] parts s = if null a then (c ++ e):parts f else a:p
"The quick brown fox jumped over the lazy dogs."
为此:
["The"," quick"," brown"," fox"," jumped"," over"," the"," lazy"," dogs."]
注意每个单词后第一个空格上的换行符
我能想到的最好的办法是:
parts "" = []
parts s = if null a then (c ++ e):parts f else a:parts b
where
(a, b) = break isSpace s
(c, d) = span isSpace s
(e, f) = break isSpace d
只是看起来有点不雅。有人能想出更好的表达方式吗?编辑----对不起,我没有读这个问题。希望这个新答案能满足你的需求
> List.groupBy (\x y -> y /= ' ') "The quick brown fox jumped over the lazy dogs."
["The"," quick"," brown"," fox"," jumped"," over"," the"," lazy"," dogs."]
库函数groupBy
采用一个谓词函数,告诉您是将下一个元素y添加到以x开头的上一个列表中,还是启动一个新列表
words2 xs = head w : (map (' ':) $ tail w)
where w = words xs
在这种情况下,我们不关心当前列表以什么开头,我们只希望在下一个元素y是空格时启动一个新列表(即,使谓词的计算结果为false)
编辑
n、 m.指出处理多个空间是不正确的。在这种情况下,您可以切换到Data.List.HT
,它具有您想要的语义
> import Data.List.HT as HT
> HT.groupBy (\x y -> y /= ' ' || x == ' ') "a b c d"
["a"," b"," c"," d"]
实现这一功能的不同语义是,x是上一个列表中的最后一个元素(您可以将y添加到该列表中,或者创建一个新列表)
下面是箭头和applicative:(不建议实际使用)
这是我的照片
break2 :: (a->a->Bool) -> [a] -> ([a],[a])
break2 f (x:(xs@(y:ys))) = if f x y then ([x],xs) else (x:u,us)
where (u,us) = break2 f xs
break2 f xs = (xs, [])
onSpace x y = not (isSpace x) && isSpace y
words2 "" = []
words2 xs = y : words2 ys where (y,ys) = break2 onSpace xs
如果你正在做很多稍微不同类型的拆分,看看这个包。该软件包允许您将此拆分定义为
split(onpublist[“”])
我喜欢拆分软件包的想法,但split(onpublist[“”])
不能满足我的要求,而且我找不到在一个或多个空间上拆分的解决方案
我也喜欢使用Data.List.HT
的解决方案,但如果可能的话,我希望远离依赖关系
我能想到的最干净的:
parts s
| null s = []
| null a = (c ++ e) : parts f
| otherwise = a : parts b
where
(a, b) = break isSpace s
(c, d) = span isSpace s
(e, f) = break isSpace d
在这里。享受吧D
words' :: String -> [String]
words' [] = []
words' te@(x:xs) | x==' ' || x=='\t' || x=='\n' = words' xs
| otherwise = a : words' b
where
(a, b) = break isSpace te
您想要的显然与
words
函数类似,因此您可能应该看看words
是如何实现的,看看是否可以做类似的事情。。。。您可以在这里看到实现:这并没有保留原来的SpaceSlook,有点像这个问题,从不久前开始<代码>链(\x y->isSpace x | |(非.isSpace)y)?
parts xs = foldr spl [] xs where
spl x [] = [[x]]
spl ' ' (xs:xss) = (' ':xs):xss
spl x xss@((' ':_):_) = [x]:xss
spl x (xs:xss) = (x:xs):xss
parts s
| null s = []
| null a = (c ++ e) : parts f
| otherwise = a : parts b
where
(a, b) = break isSpace s
(c, d) = span isSpace s
(e, f) = break isSpace d
words' :: String -> [String]
words' [] = []
words' te@(x:xs) | x==' ' || x=='\t' || x=='\n' = words' xs
| otherwise = a : words' b
where
(a, b) = break isSpace te