On Tue, Dec 10, 2013 at 6: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?
>
What about the accumulator pattern?
(defn slice
([h s n]
(slice h s n nil))
([[h & tail] s n acc]
(cond
(zero? n) acc
(zero? s) (recur tail s (dec n) (cons h acc))
:else (recur tail (dec s) n acc))))
--
--
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.