简体   繁体   English

将每个函数应用于列表Haskell的每个元素

[英]Apply each function to each element of a list Haskell

I have a list of a function like this: 我有一个这样的功能列表:

[(+1), (+2), (*4), (^2)] [(+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] 例如,我有一个像这样的列表[1..5],我希望得到此结果:[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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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