How does reduce function work?

前端 未结 9 1143
青春惊慌失措
青春惊慌失措 2020-12-01 04:25

As far as I understand, the reduce function takes a list l and a function f. Then, it calls the function f on first two elements of th

9条回答
  •  执笔经年
    2020-12-01 04:51

    Well, first of all, your reduce_func doesn't have the structure of a fold; it doesn't match your description of a fold (which is correct).

    The structure of a fold is: def foldl(func, start, iter): return func(start, foldl(func, next(iter), iter)

    Now, your fact function doesn't operate on two elements - it just calculates factorial.

    So, in sum, you're not using a fold, and with that definition of factorial, you don't need to.

    If you do want to play around with factorial, check out the y-combinator: http://mvanier.livejournal.com/2897.html

    If you want to learn about folds, look at my answer to this question, which demonstrates its use to calculate cumulative fractions: creating cumulative percentage from a dictionary of data

提交回复
热议问题