Haskell在最后发生时分割字符串 [英] Haskell split string on last occurence

查看:132
本文介绍了Haskell在最后发生时分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么办法可以将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)

请注意, 意味着它的失败。如果不可能分割(因为指定的字符不在字符串中),它会返回一个 Left 与原始列表。否则,它会返回 Right 这两个组件。 splitLast''你好美丽的世界
正确(你好,美丽,世界)
ghci> splitLast''nospaceshere!
留下无空间!


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 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)

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 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!"

这篇关于Haskell在最后发生时分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆