简体   繁体   中英

Apply each function to each element of a list Haskell

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.

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.

您也可以使用内置的zipWith函数和$运算符来执行此操作:

applyEach fs xs = zipWith ($) fs xs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM