applyAll :: [[a] -> [a]] -> [a] -> [a]
applyAll [] [] = []
applyAll [] a = a
applyAll (f1:fl) a = applyAll( (drop 1 fl)(f1 a))
我收到了这个错误
Expression : drop 1 fl (f1 a)
Term : drop
Type : Int -> [e] -> [e]
Does not match : a -> b -> c -> d
我想做那样的事情
applyAll [tail, tail, tail, tail] [1,2,3,4,5] = [5],
applyAll [(map (* 2)), (map (+ 1))] [1,2,3,4,5]) = [3,5,7,9,11]
答案 0 :(得分:5)
问题是你有
applyAll( (drop 1 fl)(f1 a))
将其解析为
applyAll ((drop 1 fl) (f1 a))
= applyAll (drop 1 fl (f1 a))
告诉编译器drop 1 fl
必须是应用于(f1 a)
的函数。但是,我们知道drop 1 fl
必须返回一个列表,所以这显然是个问题。正如@Lee指出的那样,你想要像
applyAll :: [[a] -> [a]] -> [a] -> [a]
applyAll [] a = a
applyAll (f:fs) a = applyAll fs (f a)
虽然我合并了他的前两个案例。您还可以为此函数提供更通用的类型
applyAll :: [a -> a] -> a -> a
也可以使用foldr
作为
applyAll fs a = foldr ($) a fs
然后你根本不用担心基本情况。这是有效的,因为foldr t b
获取了一个列表并用:
替换了其中的所有t
,并将[]
替换为b
,因此在此示例中:
foldr ($) [1, 2, 3, 4] (replicate 3 tail)
= foldr ($) [1, 2, 3, 4] (tail : tail : tail : [])
-- replace these ^ ^ ^ ^
-- with $ and replace the empty list |
-- with [1, 2, 3, 4]
= (tail $ (tail $ (tail $ [1, 2, 3, 4])))
= (tail $ (tail $ (tail $ [1, 2, 3, 4])))
= (tail $ (tail $ [2, 3, 4]))
= (tail $ [3, 4])
= [4]
答案 1 :(得分:1)
看起来你想要:
applyAll :: [[a] -> [a]] -> [a] -> [a]
applyAll [] [] = []
applyAll [] a = a
applyAll (f1:fl) a = applyAll fl (f1 a)
答案 2 :(得分:0)
看起来像组成列表中的函数,翻转参数,与通常的组合(.)
所以我写道:
applyAll = foldr1 (flip (.))
我一直认为使用($)
作为一个部分有点奇怪,而且难以理解