revarbat / BOSL

The Belfry OpenScad Library - A library of tools, shapes, and helpers to make OpenScad easier to use.
https://github.com/revarbat/BOSL/wiki
BSD 2-Clause "Simplified" License
571 stars 62 forks source link

cummultive sum in math.scad? #57

Closed kakila closed 4 years ago

kakila commented 4 years ago

I couldn't find a reference to a cumulative sum function. Would you consider this one? It is just a modification of sum, hence it is recursive. Example Code

function cumsum(v, i=0, pv=undef) = 
  i>=len(v)? pv : 
      cumsum(v, i+1, ((pv==undef)? [v[0]] : concat(pv, pv[len(pv)-1] + v[i])));

A drawback is that pv is growing in length, but I couldn't find a way to preallocate pv (it will have the same length as v)

kakila commented 4 years ago

I noticed that the function hangs if ever evaluate on non-list inputs, e.g.

cumsum([1:3])

This version fixes that issue, as long as the input can be converted to list

function cumsum(v, i=0, pv=undef) = 
    is_list(v) ? (i>=len(v)? pv : 
      cumsum(v, i+1, ((pv==undef)? [v[0]] : concat(pv, pv[len(pv)-1] + v[i])))) : cumsum([for (i=v) i], i=0, pv=undef);
revarbat commented 4 years ago

This was already added to BOSL2.