foldl, foldr
- Posted by bill Oct 11, 2011
- 34473 views
Jeremy raised an issue about foldl, foldr (and by extenstion zip, zip2, map, iterate,... functional extensions of Euphoria - Dec 2010).
Consider:
function add(atom X, atom a) return X+a end function function minus(atom X, atom a) return X-a end function function max(atom X, atom a) if X >= a then return X end if return a end function constant ADD = routine_id("add") constant MINUS = routine_id("minus") constant MAX = routine_id("max") function foldl(sequence S, integer op, atom acc) atom ACC = acc for i = 1 to length(S) do ACC = call_func(op,{ACC,S[i]}) end for return ACC end function ? foldl({1,2,3,4,5,6,7,8,9}, ADD, 0) printf(1,"------------------\n") ? foldl({1,-2,3,-4,5,-6,7,-8,9,-10,11}, MINUS, 0) printf(1,"------------------\n") ? foldl({1,-2,3,-4,5,-6,7,-8,9,-10,11}, MAX, 0) printf(1,"------------------\n")
Of course we could use a macro to replace the framework so we would be saying:
foldl(S,+,0) effectively.