gpt4 book ai didi

list - Haskell 在最后一次出现时拆分字符串

转载 作者:行者123 更新时间:2023-12-01 07:53:02 25 4
gpt4 key购买 nike

有什么办法可以将 Haskell 中最后一次出现的给定字符的字符串拆分为 2 个列表?
例如,我想将空间上的列表“a b c d e”拆分为(“a b c 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)

注意这是 总计 并清楚地表明它的失败。如果无法拆分(因为指定的字符不在字符串中),则返回 Left与原始列表。否则,它返回 Right与两个组件。
ghci> splitLast ' ' "hello beautiful world"
Right ("hello beautiful","world")
ghci> splitLast ' ' "nospaceshere!"
Left "nospaceshere!"

关于list - Haskell 在最后一次出现时拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40030460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com