(defun bang (n)
(loop for x from 1 to n
for r = 1 then (* x r)
finally (return r)))
Pascal Costanza wrote:
(defun bang (n)
(loop for x from 1 to n
for r = 1 then (* x r)
finally (return r)))
(define (bang n)
(if (< n 2) 1 (* n (bang (- n 1)))))
(bang 5) ===> 120
I'm not advocating tail-recursion instead of specialized iteration mechanisms closer to the problem domain. I'm just saying tail-
recursion code isn't anywhere as low-level as you're making it up to
be.
It actually is, and your posting below shows it very nicely.
Here is a nice example using loop:
(loop for (key value) on property-list by #'cddr
unless (member key excluded-keys)
append (list key value)) ; [1]
As a function:
(defun filter (excluded-keys property-list)
(loop for (key value) on property-list by #'cddr
unless (member key excluded-keys)
nconc (list key value)))
(filter '(c d) '(a 1 b 2 b 3 c 4 d 5 c 6))(A 1 B 2 B 3)
The result is a correct property list
Pascal Costanza wrote:
I'm not advocating tail-recursion instead of specialized iteration mechanisms closer to the problem domain. I'm just saying tail-
recursion code isn't anywhere as low-level as you're making it up to
be.
It actually is, and your posting below shows it very nicely.
Here is a nice example using loop:
(loop for (key value) on property-list by #'cddr
unless (member key excluded-keys)
append (list key value)) ; [1]
As a function:
(defun filter (excluded-keys property-list)
(loop for (key value) on property-list by #'cddr
unless (member key excluded-keys)
nconc (list key value)))
(filter '(c d) '(a 1 b 2 b 3 c 4 d 5 c 6))(A 1 B 2 B 3)
The result is a correct property list
Gauche Scheme
(define (remove-props bad-keys prop-list)
(concatenate
(remove (^p (member (car p) bad-keys))
(slices prop-list 2))))
(remove-props '(c d) '(a 1 b 2 b 3 c 4 d 5 c 6))
===>
(a 1 b 2 b 3)
does this look like assembly?
(define (! n)
(let loop ((x n) (r 1))
(if (zero? x) r
(loop (- x 1) (* x r)))))
Yes, it does compared with
(defun factorial (n)
(loop for n from 1 upto n
and f = 1 then (* f n)
finally (return f)))
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 388 |
Nodes: | 16 (2 / 14) |
Uptime: | 10:07:40 |
Calls: | 8,221 |
Files: | 13,122 |
Messages: | 5,872,631 |