Integral Calculus in Lambda Calculus (Lisp)
jng.imagine27.com
jng.imagine27.com
(defparameter small-dx 0.00001)
(defun integrate (f a b &optional (dx small-dx))
"integrate a function f from a to b"
(loop for x from a to b by dx sum (* dx (funcall f x))))
Then you can use it like: (flet ((f1 (x) 1)
(f2 (x) (expt x 2))
(f3 (x) (* x (exp (expt x 2)))))
(format t "f1: ~A, f2: ~A, f3: ~A~%"
(integrate #'f1 0 5)
(integrate #'f2 0 5)
(integrate #'f3 0 5)))
In conclusion, CL is not Scheme.(Edit: Initially I said that the code doesn't compile. It does -- storing functions in the value slot of variables threw me off a bit. Very Scheme-like.)
Actually the loop macro in CL can be a very contentious topic. I'd hardly refer to the loop macro as idiomatic. Imperative and functional styles in CL can both be idiomatic.
Anyway who said CL was Scheme ?
Your style strongly hints at a Scheme background. Nothing you do is wrong, but if you read a bunch of Lisp code, you wouldn't see many people doing things the way you did. OTOH, if you read a bunch of Scheme code, it would look exactly like yours.
Also, I don't think the use of loop is a point of contention. LOOP is in the CL spec, tail recursion isn't. (The ITERATE package is a nicer loop, but the idea is the same.)
Yes tail-recursion is not part of the spec along with many other implementation aspects that probably should be.
Also, absence of tail-call elimination in the spec doesn't have to stop you from using it, if your compiler supports it. We all love Common Lisp, but usually not "warts and all"; we all end up using our personally "attractive" subset. I personally code in Dylan with s-exp notation that happens to compile under SBCL :-)
(defun integrate (f a b &aux (dx *small-dx*))
(labels ((rec (x sum)
(if (> x b) sum
(rec (+ x dx) (+ sum (* (funcall f x) dx))))))
(rec a 0)))See Norvig's "Paradigms of Artificial Intelligence Programming - Case Studies in Common Lisp", Chapter 8 - Symbolic Mathematics : A Simplification Program, 8.6 - Integration, page 252.
See Norvig's "Paradigms of Artificial Intelligence Programming - Case Studies in Common Lisp", Chapter 8 - Symbolic Mathematics : A Simplification Program, 8.6 - Integration, page 252.