Ask HN: How to compose two mapping functions into a third?
https://news.ycombinator.com/item?id=393731I'd like a good way to do the following, where "good" means some balance of simple and efficient.
I have a bunch of mapping functions. Each takes an integer interval [START,END] and a function FN to call once for each integer N in the interval, passing two arguments: N and some value computed from N.
For example, say MAP1 works this way, passing N and N+10 to the function provided:
(defun map1 (fn start end)
(loop for n from start to end do
(funcall fn n (+ n 10))))
...so if you gave MAP1 a function that printed out its arguments, you'd get this: (map1 (lambda (n val) (format t "~a ~a~%" n val)) 1 3) =>
1 11
2 12
3 13
Now say MAP2 does the same, only instead of N+10 it passes N^2: (defun map2 (fn start end)
(loop for n from start to end do
(funcall fn n (expt n 2))))
(map2 (lambda (n val) (format t "~a ~a~%" n val)) 1 3) =>
1 1
2 4
3 9
What I want is a way to make a new mapping function MAP3 that works the same way but composes the computations in MAP1 and MAP2. For simplicity, say I just want to add the values computed by MAP1 and MAP2. Then MAP3 should do this: (map3 (lambda (n val) (format t "~a ~a~%" n val)) 1 3) =>
1 12
2 16
3 22
Any nice solutions? The rules are: (1) it's ok to modify the definition of "mapping function", as long as it's simple, and (2) I don't want to have to make a local copy of everything one of these functions does (because the intervals can be large).Edit: A solution in Common Lisp would be nice, but I'm interested in good approaches to this in general. Perhaps coroutines?