On Tue, Dec 10, 2013 at 11:09 PM, Glen Mailer <[email protected]> wrote:
> I was recently working on some toy recursion problems, when I ran into a
> function that I can express simply using normaly recursion, but I can't seem
> to convert it into a form that works nicely with loop/recur.
>
> It's certainly not the right way to solve this problem, but I'm intrigued to
> see what this pattern looks like with explicit tail calls:
>
> Problem:
> Extract a slice from a list
> (slice [ 3 4 5 6 7 8 9 ] 2 4)
> ;=> [ 5 6 7 8 ]
>
> Normal Recursive Solution:
> (defn slice [[h & tail] s n]
> (cond
> (zero? n) nil
> (zero? s) (cons h (slice tail s (dec n)))
> :else (slice tail (dec s) n)))
>
> What would the tail recursive version of this look like? can it retain the
> nice readability of this form?
>
Try this (not tested, might be missing parens and whatnot):
(defn slice [x s n]
(loop [[h & tail] x, s s, n n, acc []]
(cond
(zero? n) acc
(zero? s) (recur tail s (dec n) (conj acc h))
:else (recur tail (dec s) n acc))))
Few notes:
- When trying for tail recursions, use an accumulator. The accumulator
carries the eventual result, which is returned at the base case.
- Since we're destructuring into head and tail, I used vectors. conj
will push to the end of the vector.
- In Clojure, vectors tend to be more natural than lists. Accumulating
into lists usually requires a reverse in the base case.
Regards,
Vincent Chen
--
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.