組み込み関数:reduce

まず、組み込み関数 reduce のヘルプ情報を確認します。

>>> help(reduce)
Help on built-in function reduce in module __builtin__:

reduce(...)
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

《Note》 組み込み関数 reduce は、初期の Python から導入されています。inject:into:/Smalltalk のような汎用性はありませんが、軽微な問題解決を図りたいときには重宝します。また、OCL にも、同様の iterate 操作が規定されています。 □

例題を使って、その動作を確認してみましょう。