On Tue, Dec 10, 2013 at 6:29 PM, Vincent Chen <noodle...@gmail.com> wrote:

> 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.


If you're going to go with vectors, why not go transient as well?

(defn slice [x s n]
  (loop [[h & tail] x, s s, n n, acc (transient [])]
    (cond
      (zero? n) (persistent! acc)
      (zero? s) (recur tail s (dec n) (conj! acc h))
      :else (recur tail (dec s) n acc))))

Might be more runtime efficient.

-- 
-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
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 clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to