迭代产品 [英] product of list iteratively
问题描述
我从一个简单的例子列表的产品开始。
product :: [Integer] - >整数
product [] = 1
product(x:xs)= x * product xs
我很快就完成了。
另一种方法是API中的产品功能。 (产品列表 - >产品)
我想知道是否有另外一种迭代的方式来解决我的问题吗?
您可以使用折叠:
product :: Num a => [a] - > a
product xs = foldl(*)1 xs
这也可以严格使用 foldl'
或 foldr
,差异主要是表现,但由于您刚开始时我会跳过这次讲座。
那么折叠是做什么的?让我们从 foldl
的基本定义开始:
foldl ::( a→b→a)→> a - > [b] - > a
foldl f acc [] = acc
foldl f acc(x:xs)= foldl f(f acc x)xs
这是一个函数 f :: a - > b - >一个带有累加器的
和一个从值列表中提供给它的附加值。它迭代地应用这个函数,在每一步生成一个新的累加器,直到它在列表中的值不足。对于(*)
,它看起来像
> foldl(*)1 [1,2,3,4]
| (*)(1 * 1)[2,3,4] = foldl(*)1 [2,3,4]
| foldl(*)(1 * 2)[3,4] = foldl(*)2 [3,4]
| foldl(*)(2 * 3)[4] = foldl(*)6 [4]
| foldl(*)(6 * 4)[] = foldl(*)24 []
| 24
我应该补充说明,这不是它在内存中的执行方式,除非您使用 foldl'
,这是严格的版本,但更容易遵循这种方式。
I'm trying to learn coding in Haskell.
I started with an easy example "the product of a list".
product :: [Integer] -> Integer
product [] = 1
product (x:xs) = x * product xs
I finished this quickly. Another way is the product function in the API. (product List -> product)
I wonder if there is another iterative way to solve my problem?
You can use a fold:
product :: Num a => [a] -> a
product xs = foldl (*) 1 xs
This can also be done strictly with foldl'
or foldr
, the differences mostly are performance, but since you're just starting out I'll skip that lecture this time.
So what does a fold do? Let's start with the basic definition of foldl
:
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f acc [] = acc
foldl f acc (x:xs) = foldl f (f acc x) xs
What this does is takes a function f :: a -> b -> a
which takes an accumulator and an additional value, which is fed to it from the list of values. It iteratively applies this function, generating a new accumulator at each step, until it runs out of values in the list. For (*)
it looks something like
> foldl (*) 1 [1, 2, 3, 4]
| foldl (*) (1 * 1) [2, 3, 4] = foldl (*) 1 [2, 3, 4]
| foldl (*) (1 * 2) [3, 4] = foldl (*) 2 [3, 4]
| foldl (*) (2 * 3) [4] = foldl (*) 6 [4]
| foldl (*) (6 * 4) [] = foldl (*) 24 []
| 24
I should add that this isn't exactly how it's performed in memory unless you use foldl'
, which is the strict version, but it's easier to follow this way.
这篇关于迭代产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!