python - Why is the initial value to the reduce function not mandatory? -
in haskell, initial value foldl operator mandatory
prelude> foldl (+) 0 [1] 1 prelude> foldl (+) 0 [] 0 prelude> :t foldl (a -> b -> a) -> -> [b] -> but in reduce function (or functools.reduce), initial value optional
reduce(function, sequence[, initial]) -> value the time initial value required when sequence empty. congruent behaviour in haskell. reduce in python assumes if sequence of size 1; handles these corner cases internally ?
>> reduce(operator.sub, [1]) 1 >> reduce(operator.mul, [1]) 1 >> reduce(operator.add, [1]) 1
from manual:
if initializer not given , iterable contains 1 item, first item returned
i want comment on this:
the time initial value required when sequence empty
this not entirely true. in fold operation assume have earlier result work with. if fold operation appending elements list initial element can empty list, can add elements that. more generally, initial value needed when return type of function differs type of elements in list.
Comments
Post a Comment