我有一个这样的函数列表:
[(+1),(+ 2),(*4),(^ 2)]
我想将每个函数应用于另一个列表的每个元素.例如我有一个这样的列表[1..5],我希望得到这个结果:[2,4,12,16]
这就是我已经尝试过的.
applyEach :: [(a -> b)] -> [a] -> [b]
applyEach _ [] = []
applyEach (x:xs) (y:ys) = x y : applyEach xs ys
Run Code Online (Sandbox Code Playgroud)
我不知道是什么问题,我们有一个在线表面,我们必须放置代码并测试我们的submision,并且只说我的代码没有通过.
当列表长度相同或第二个列表比第一个列表短时,您的函数可以正常工作:
> applyEach [(+1), (+2), (*4), (^2)] [1..4]
[2,4,12,16]
> applyEach [(+1), (+2), (*4), (^2)] [1..3]
[2,4,12]
Run Code Online (Sandbox Code Playgroud)
但是你没有处理第二个列表更长的情况,就像在你的例子中一样:
> applyEach [(+1), (+2), (*4), (^2)] [1..5]
[2,4,12,16*** Exception: H.hs:(2,1)-(3,47): Non-exhaustive patterns in function applyEach
Run Code Online (Sandbox Code Playgroud)
您需要在函数中再添加一个等式来处理这种情况.
您也可以使用内置zipWith函数和$运算符执行此操作:
applyEach fs xs = zipWith ($) fs xs
Run Code Online (Sandbox Code Playgroud)