accumulator

なるほど。accumulateってこう書くのか。

# 繰り返し版
def accumulate(combiner, null_value, term, a, next, b):
  r = null_value
  while a <= b:
    r = combiner(r, term(a))
    a = next(a)
  return r

# 再帰版
def accumulate_r(combiner, null_value, term, a, next, b):
  if a > b:
    return null_value
  return combiner(term(a), accumelate_r(combiner, null_value, term, next(a), next, b))

def sum(term, a, next, b):
  return accumulate(lambda x, y: x + y, 0, lambda x: x, a, next, b)

def product(term, a, next, b):
  return accumulate(lambda x, y: x * y, 1, lambda x: x, a, next, b)

しかし、Pythonの組み込み関数に、和はsumがあるけど、積のproductにあたる関数がないのは残念。Pythonにおけるaccumulate関数ってreduceだと思うのだけど、結局productって、reduce(int.__mul__, seq)しかないのかな?