Arc Forumnew | comments | leaders | submitlogin
4 points by waterhouse 5138 days ago | link | parent

Function: (accumulate comb f xs init next done) : A function useful for expressing many accumulation patterns: mapping, summation, products, and others. You use next to iterate over xs until xs is done, and the results are mapped by f and comb-ined one by one with init. For example:

  (map f xs) = (rev:accumulate cons f:car xs nil cdr no)
  (factorial n) = (accumulate * idfn 1 1 inc [> _ n])
  (rev xs) = (accumulate cons car xs nil cdr no)
  (range a b) = (rev:accumulate cons idfn a nil inc [> _ b])
  (len xs) = (accumulate + [idfn 1] xs 0 cdr no)
  (sum f a b) = (accumulate + f a 0 inc [> _ b])
  (sumlist f xs) = (accumulate + f:car xs 0 cdr no)
  (mapn f a b) = (rev:accumulate cons f a nil inc [> _ b])
I use this a fair amount. See also: http://arclanguage.org/item?id=10791

  (def accumulate (comb f xs init next done)
    ((afn (xs total)
       (if (done xs)
           total
           (self (next xs) (comb (f xs) total))))
     xs init))