Hello .. I am learning how to use the ITERATE macro and would like to
see an iterative version of the fib function. I've tried myself to
write it but haven't had much luck. I would like to see what others
come up with .. thanks.
On Jun 26, 8:40 am, msingh <··········@gmail.com> wrote:
> Hello .. I am learning how to use the ITERATE macro and would like to
> see an iterative version of the fib function. I've tried myself to
> write it but haven't had much luck. I would like to see what others
> come up with .. thanks.
It's actually a little trickier than I expected. The trick for doing
this sort of thing with ITERATE, since you lack the ability to step
variables in parallel, is to use the :PREVIOUS and :BACK keywords,
which together allow you to get at the value of a variable from the
previous iterations. The result looks something like this:
(defun fiberate (n)
"Returns the Nth Fibonacci number."
(iter
(repeat n)
(for a :initially 1 :then (+ a b))
(for b :previous a :back 2 :initially 0)
(finally (return a))))
Cheers,
Pillsy
> It's actually a little trickier than I expected. The trick for doing
> this sort of thing with ITERATE, since you lack the ability to step
> variables in parallel, is to use the :PREVIOUS and :BACK keywords,
> which together allow you to get at the value of a variable from the
> previous iterations. The result looks something like this:
>
> (defun fiberate (n)
> "Returns the Nth Fibonacci number."
> (iter
> (repeat n)
> (for a :initially 1 :then (+ a b))
> (for b :previous a :back 2 :initially 0)
> (finally (return a))))
>
> Cheers,
> Pillsy
That's beautiful. Thanks for sharing your code! I almost had the same
code but I wasnt going :back enough.
Arbscht from Freenode also wrote two versions of fib:
(defun fib (n)
(iter (repeat n)
(for a initially 0 then b)
(for b initially 1 then (+ ap b))
(for ap previous a)
(finally (return a))))
(defun fib (n)
(iter (repeat n)
(for (a b) :initially '(1 0) :then (list (+ a b) a))
(finally (return b))))
On Jun 27, 5:05 am, msingh <··········@gmail.com> wrote:
> Arbscht from Freenode also wrote two versions of fib:
[...]
> (defun fib (n)
> (iter (repeat n)
> (for (a b) :initially '(1 0) :then (list (+ a b) a))
> (finally (return b))))
ITERATE also allows for destructuring VALUES forms, like so:
(defun fib-vals (n)
(iter (repeat n)
(for (values a b)
:initially (values 1 0)
:then (values (+ a b) a))
(finally (return a))))
This conses a little less (though the difference isn't as striking as
I thought it would be), and I find it a little more aesthetically
pleasing.
Cheers,
Pillsy