Reputation: 3
applyAll :: [[a] -> [a]] -> [a] -> [a]
applyAll [] [] = []
applyAll [] a = a
applyAll (f1:fl) a = applyAll( (drop 1 fl)(f1 a))
I got this error
Expression : drop 1 fl (f1 a)
Term : drop
Type : Int -> [e] -> [e]
Does not match : a -> b -> c -> d
I want to do something like that
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]
Upvotes: 0
Views: 108
Reputation: 568
It looks like composing the functions in the list, with arguments flipped, compared to usual composition (.)
So I'd write :
applyAll = foldr1 (flip (.))
I always thought using ($)
as a section is a bit weird, and harder to understand
Upvotes: 0
Reputation: 54078
The problem is that you have
applyAll( (drop 1 fl)(f1 a))
This is parsed as
applyAll ((drop 1 fl) (f1 a))
= applyAll (drop 1 fl (f1 a))
Which tells the compiler that drop 1 fl
must be a function applied to (f1 a)
. However, we know that drop 1 fl
must return a list, so this obviously is a problem. As @Lee has pointed out, you want something like
applyAll :: [[a] -> [a]] -> [a] -> [a]
applyAll [] a = a
applyAll (f:fs) a = applyAll fs (f a)
Although I've merged his first two cases. You can also give this function the more general type
applyAll :: [a -> a] -> a -> a
This can alternatively be implemented using foldr
as
applyAll fs a = foldr ($) a fs
And then you don't have to worry about base cases at all. This works because foldr t b
takes a list and replaces all the :
in it with t
, and replaces []
with b
, so in this example:
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]
Upvotes: 5
Reputation: 144206
It looks like you want:
applyAll :: [[a] -> [a]] -> [a] -> [a]
applyAll [] [] = []
applyAll [] a = a
applyAll (f1:fl) a = applyAll fl (f1 a)
Upvotes: 1