Apply each function to each element of a list Haskell

Tag: haskell Author: ymltwp1xw Date: 2014-04-08

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.

homework? in this order, do: 1. look for answers or hints in the course materials that were certainly provided, 2. discuss with your fellow students, 3. ask your instructor.
There's already a function that does exactly that in the standard libraries. Though I suppose it's at a higher level of abstraction than you're currently used to.

Best Answer

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]
> applyEach [(+1), (+2), (*4), (^2)] [1..3]

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.


Ohhh well, really i forgot to add this case applyEach [] _ = [], thank you, you saved my life =)

Other Answer1

You can also do this with the built-in zipWith function and the $ operator:

applyEach fs xs = zipWith ($) fs xs