Haskell在最后发生时分割字符串 [英] Haskell split string on last occurence
问题描述
有没有什么办法可以将Haskell中String的最后一次出现的字符分割成2个列表?
例如,我想将空间列表a b c d e分隔为(a b c d,e)。
感谢您的回答。
我不知道为什么解决方案建议如此复杂。只需 一次两次遍历:
splitLast :: Eq a => a - > [a] - >或者[a]([a],[a])
splitLast c'= foldr go(Left [])
其中
go c(Right(f,b))= Right c:f,b)
去c(左s)| c'== c = Right([],s)
|否则=左(c:s)
请注意, Is there any way I can split String in Haskell on the last occurrence of given character into 2 lists?
For example I want to split list "a b c d e" on space into ("a b c d", "e").
Thank you for answers. I'm not sure why the solutions suggested are so complicated. Only Note this is total and clearly signifies its failure. When a split is not possible (because the character specified wasn't in the string) it returns a
这篇关于Haskell在最后发生时分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Left
与原始列表。否则,它会返回 Right
这两个组件。 splitLast''你好美丽的世界
正确(你好,美丽,世界)
ghci> splitLast''nospaceshere!
留下无空间!
one two traversals are needed: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)
Left
with the original list. Otherwise, it returns a Right
with the two components.ghci> splitLast ' ' "hello beautiful world"
Right ("hello beautiful","world")
ghci> splitLast ' ' "nospaceshere!"
Left "nospaceshere!"