The first example uses a recursive definition to sum the integers 1 to k. The divide and conquer solution has two cases.
When there are no integers to be added, the result should be zero.
When there are k (k>0)
integers,
the solution can be written as k+sum(k-1)
.
Following are the Scheme and J programs for summing the integers 1 to k.
(define sum (lambda(n) (if (= n 0) 0 (+ n (sum (- n 1))))))
Program sum
(Scheme Version)
sum =: monad define script if. y. = 0 do. 0 else. y. + sum y. - 1 end. )
Program sum
(J Version)