Discussion:
applying f to f n times - best argument order?
(too old to reply)
B. Pym
2024-08-25 10:04:49 UTC
Permalink
You want to bounce the arguments down into the recursive call, not a
list of them as one argument, right?
(defun ncall (f n &rest data)
(loop repeat n
for result = (apply f data) then (funcall f result)
finally (return result)))
(define (feedback func init bottom-i :optional (top-i #f))
(let ((result init))
(if top-i
(do ((i bottom-i (+ 1 i)))
((> i top-i) result)
(set! result (func result i)))
(dotimes (i bottom-i)
(set! result (func result))))
result))


;; factorial
(feedback (lambda (prod i) (* i prod)) 1 1 5)
===>
120


(feedback (lambda (prod) (* 2 prod)) 1 8)
===>
256


;; Newton square root
(let ((x 99.0))
(feedback
(lambda (guess) (/. (+ guess (/. x guess)) 2.0))
1.0 8))
===>
9.9498743710662

(sqrt 99)
===>
9.9498743710662
Jeff Barnett
2024-08-25 18:50:21 UTC
Permalink
Post by B. Pym
You want to bounce the arguments down into the recursive call, not a
list of them as one argument, right?
(defun ncall (f n &rest data)
(loop repeat n
for result = (apply f data) then (funcall f result)
finally (return result)))
(define (feedback func init bottom-i :optional (top-i #f))
(let ((result init))
(if top-i
(do ((i bottom-i (+ 1 i)))
((> i top-i) result)
(set! result (func result i)))
(dotimes (i bottom-i)
(set! result (func result))))
result))
Isn't this where you usually jump in and loudly proclaim "SHORTER!"? You
might as well repeat it hear since you are not shorter a significant
amount of the time.

Off topic question: Any job offers recently?
Post by B. Pym
;; factorial
(feedback (lambda (prod i) (* i prod)) 1 1 5)
===>
120
(feedback (lambda (prod) (* 2 prod)) 1 8)
===>
256
;; Newton square root
(let ((x 99.0))
(feedback
(lambda (guess) (/. (+ guess (/. x guess)) 2.0))
1.0 8))
===>
9.9498743710662
(sqrt 99)
===>
9.9498743710662
--
Jeff Barnett
Madhu
2024-08-26 05:04:31 UTC
Permalink
memo: there's no glory in trolling WJ

* Jeff Barnett <vafudd$220kj$***@dont-email.me> :
Wrote on Sun, 25 Aug 2024 12:50:21 -0600:

Loading...