我是haskell的新手,想要将数组中的所有数字相乘.例如.:
阵:
[3,2,4] //3*2*4
Run Code Online (Sandbox Code Playgroud)
产量
24
Run Code Online (Sandbox Code Playgroud)
谢谢,非常感谢任何帮助.
在Haskell中有很多方法可以做到这一点.例如,您可以使用:
product [3,2,4]
Run Code Online (Sandbox Code Playgroud)
或者等价的
foldr (*) 1 [3,2,4]
Run Code Online (Sandbox Code Playgroud)
或者递归地:
prod [] = 1
prod (x : xs) = x * prod xs
Run Code Online (Sandbox Code Playgroud)
函数foldr就是所谓的列表变形.要理解foldr,我们需要首先理解列表构造函数.在Haskell中,[3,2,4]是一个语法糖3 : 2 : 4 : [],其中:是list-cons构造函数,[]是空列表.应用程序foldr f v将按:功能f和空列表替换列表中的每个匹配项v.其定义如下:
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f v [] = v -- equation 1
foldr f v (x:xs) = f x (foldr f v xs) -- equation 2
Run Code Online (Sandbox Code Playgroud)
例如,考虑foldr (*) 1 [3,2,4]:
foldr (*) 1 [3,2,4] =
3 * (foldr (*) 1 [2,4]) = (by equation 2 of foldr)
3 * (2 * (foldr (*) 1 [4])) = (by equation 2 of foldr)
3 * (2 * (4 * (foldr (*) 1 []))) = (by equation 2 of foldr)
3 * (2 * (4 * 1)) = (by equation 1 of foldr)
= 24
Run Code Online (Sandbox Code Playgroud)