【发布时间】:2019-03-27 15:52:12
【问题描述】:
我在尝试理解 Haskell 上的折叠实现时遇到了很多问题。我需要使用具有此输出的 fold 的两个函数
> runLengthEncode "aaaaaaabbb"
[(7,'a'),(3,'b')]
> runLengthDecode [(1,'h'), (5,'i')]
"hiiiii"
所以我所做的是首先编写函数,就像我对模式匹配所做的那样(它们有效),但现在我不知道如何使用左折叠或右折叠来“翻译”它。
runLengthEncode :: String -> [(Int,Char)]
runLengthEncode [] = []
runLengthEncode (x:xs) = runLengthEncode 1 x xs
where
runLengthEncode n x [] = [(n,x)]
runLengthEncode n x (y:ys) | x == y = runLengthEncode (n + 1) y ys
| otherwise = (n,x) : runLengthEncode 1 y ys
runLengthDecode :: [(Int,Char)] -> String
runLengthDecode [] = []
runLengthDecode ((a,b):xs) = replicate a b ++ (runLengthDecode xs)
【问题讨论】:
-
您应该发布您使用折叠的尝试,并解释您遇到的问题。
-
您有机会查看我在上述评论中提供的链接吗?通过不接受答案,您可以保持问题的开放性,向社区表明这些问题仍未解决。他们还在吗?如果是这样,为什么在 cmets 中没有后续问题或要求澄清?
标签: function haskell functional-programming refactoring fold