In Java terms, we can't use the return statement,
so sum_odd
can't return a value. The solution is to give sum_odd
an additional argument, k, called the continuation that
receives the result of sum_odd and does something with it.
Converting an algorithm to use this continuation passing style has proved to be very important in program transformation and compiling.
Here are two versions of sum_odd using this style.
printer = ((int) x) { System.out.println(x) }
sum_odd = (es sum k) {
if (isNull(es)) k(sum)
else {
e = car(es)
newSum = if (isOdd(e)) sum + e
else e
sum_odd (cdr(es) newSum k)
}
}
// Invoke like:
sum_odd(items 0 printer)
Here's what this might look like in Common Lisp:
(defun main ()
(sum-odd '(2 9 3 8 4) (lambda (v) (print v))))
(defun sum-odd (elements k)
(sum-odd-1 elements 0 k))
(defun sum-odd-1 (elements sum k)
(if (null elements) (call k sum)
(sum-odd-1 (cdr elements)
(let ((e (car elements)))
(if (oddp e) (+ sum e) sum))
k))))