Reputation: 824
I have a list of a function like this:
[(+1), (+2), (*4), (^2)]
And i want to apply each function to each element of an another list. For example i have a list like this [1..5], i want to get this as result: [2,4,12,16]
This is what i tryed already.
applyEach :: [(a -> b)] -> [a] -> [b]
applyEach _ [] = []
applyEach (x:xs) (y:ys) = x y : applyEach xs ys
I don't know what is the problem, we have a online surface where we have to place the code and it test our submision, and only said that my code isn't pass.
Upvotes: 0
Views: 1790
Reputation: 83527
You can also do this with the built-in zipWith
function and the $
operator:
applyEach fs xs = zipWith ($) fs xs
Upvotes: 6
Reputation: 139840
Your function works fine when the lists are the same length, or when the second list is shorter than the first:
> applyEach [(+1), (+2), (*4), (^2)] [1..4]
[2,4,12,16]
> applyEach [(+1), (+2), (*4), (^2)] [1..3]
[2,4,12]
But you're not dealing with the case where the second list is longer, as it is in your example:
> applyEach [(+1), (+2), (*4), (^2)] [1..5]
[2,4,12,16*** Exception: H.hs:(2,1)-(3,47): Non-exhaustive patterns in function applyEach
You need to add one more equation to your function to handle this case.
Upvotes: 8