有人可以解释一下如何intercalate使用fold 编写函数吗?另外,我听说过foldr或foldl; 在这种情况下,最适合使用其中的哪一个?
这是我尝试递归的方法:
intercalate :: [a] -> [[a]] -> [a]
intercalate s [] = []
intercalate s [x] = x
intercalate s (x:xs) = x ++ s ++ (intercalate s xs)
Run Code Online (Sandbox Code Playgroud) 我在尝试了解Haskell上的折叠实现时遇到很多问题。我需要使用具有此输出的fold两个函数
> runLengthEncode "aaaaaaabbb"
[(7,'a'),(3,'b')]
> runLengthDecode [(1,'h'), (5,'i')]
"hiiiii"
Run Code Online (Sandbox Code Playgroud)
因此,我要做的就是像编写模式匹配一样(工作)先编写函数,但是现在我不知道如何使用向左折叠或向右折叠来“翻译”该函数。
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)
Run Code Online (Sandbox Code Playgroud) 我正在审查考试,并且其中一个实践问题要求写类型声明
mystery :: ---complete here----
mystery x p
| p (head x) = tail x
| otherwise = head x : mystery (tail x) p
Run Code Online (Sandbox Code Playgroud)
不看答案,我认为谜题的类型是:
mystery:: [a] -> a -> [a]
但是当我查看要比较的解决方案时:
mystery:: [a] -> (a -> Bool) -> [a]
为什么a -> Bool呢?在代码行中可以告诉我Bool在类型声明中考虑什么?