can*_*dry 3 python functional-programming
在haskell中,foldl运营商的初始值显然是强制性的
Prelude> foldl (+) 0 [1]
1
Prelude> foldl (+) 0 []
0
Prelude> :t foldl
(a -> b -> a) -> a -> [b] -> a
Run Code Online (Sandbox Code Playgroud)
但是在reduce函数(或functools.reduce)中,初始值是可选的
reduce(function, sequence[, initial]) -> value
Run Code Online (Sandbox Code Playgroud)
需要初始值的唯一时间是序列为空.这与haskell中的行为一致.reduce在python中是否假设序列的大小为1; 然后它在内部处理这些角落案件?
>> reduce(operator.sub, [1])
1
>> reduce(operator.mul, [1])
1
>> reduce(operator.add, [1])
1
Run Code Online (Sandbox Code Playgroud)
回想一下,在Haskell中有两个版本的折叠 - 一个采用某种结果类型的种子,另一种假设种子是序列的第一个元素.
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr k z = go
where
go [] = z
go (y:ys) = y `k` go ys
Run Code Online (Sandbox Code Playgroud)
和
foldr1 :: (a -> a -> a) -> [a] -> a
foldr1 _ [x] = x
foldr1 f (x:xs) = f x (foldr1 f xs)
foldr1 _ [] = errorEmptyList "foldr1"
Run Code Online (Sandbox Code Playgroud)
foldr 使用序列的初始元素作为第一个状态.
还有一个重要的区别:通过使用序列的第一个元素作为输入状态,foldr1约束返回与输入列表相同类型的数组.foldr但是可以返回一些不同的类型.
| 归档时间: |
|
| 查看次数: |
1723 次 |
| 最近记录: |