【发布时间】:2016-06-02 01:45:08
【问题描述】:
这里是 Haskell 新手
我正在用 haskell 解决这个问题:
(**) Eliminate consecutive duplicates of list elements.
If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.
Example:
* (compress '(a a a a b c c a a d e e e e))
(A B C A D E)
解决方案(我必须查找)使用 foldr:
compress' :: (Eq a) => [a] -> [a]
compress' xs = foldr (\x acc -> if x == (head acc) then acc else x:acc) [last xs] xs
这个foldr,根据解法,有两个参数,x和acc。似乎所有 foldr 都采用这些参数;这有什么例外吗?像一个需要 3 个或更多的文件夹?如果不是,这个约定是不是多余的,公式可以用更少的代码编写吗?
【问题讨论】:
-
您可以设想许多 foldr 接受超过 2 个参数的情况,例如
foldr (\f g x -> f (g x)) (\x -> x)。 -
我不确定我是否会使用
foldr来实现您的compress功能。如果参数是空列表会发生什么? -
foldr实现会很好,您只需要首先有一个模式可以处理空列表的情况compress' [] = [] -
@SimonGibbons,另一种适用于任何
Foldable并且与列表融合配合良好的方法是使用Maybe作为累加器。