rai*_*ker 3 haskell split list
有没有什么办法可以将最后一次出现给定字符的Haskell中的String拆分成2个列表?例如,我想将空格中的列表"abcd e"拆分为("abc d","e").谢谢你的回答.
我不确定为什么建议的解决方案如此复杂.只有一个两次遍历需要:
splitLast :: Eq a => a -> [a] -> Either [a] ([a],[a])
splitLast c' = foldr go (Left [])
where
go c (Right (f,b)) = Right (c:f,b)
go c (Left s) | c' == c = Right ([],s)
| otherwise = Left (c:s)
Run Code Online (Sandbox Code Playgroud)
请注意,这是完全的,并清楚地表明其失败.如果无法进行拆分(因为指定的字符不在字符串中),则返回Left带有原始列表的a.否则,它返回Right带有两个组件的a.
ghci> splitLast ' ' "hello beautiful world"
Right ("hello beautiful","world")
ghci> splitLast ' ' "nospaceshere!"
Left "nospaceshere!"
Run Code Online (Sandbox Code Playgroud)