I'm stuck trying to write a Clojure function that takes a span from a collection or vector. For example I'd like to manipulate a collection such as (:a :b :c :d :e :f :g :h) by taking the second element through the fifth in steps of two. Thus, outputting (:b :d).
Asked
Active
Viewed 57 times
0
-
There are lots of ways to do it. You could just walk through the sequence, collecting the elements you want as you go, keeping track of the counts. Good recursion exercise. Think about how you would do it in an imperative language, and then just translate that into recursion. Or you could use Chiron's suggestion, along with `drop` and `take`. I coded up a solution for myself, but I'm wondering whether this might be homework. If so, these hints should be enough to work it out, or provide a basis for new questions. – Mars Nov 12 '13 at 06:26
-
Then again, is anybody using Clojure as a course language? Dirk Geurs's answer is what I would have suggested. – Mars Nov 13 '13 at 05:47
-
Any particular reason you haven't accepted any answers yet? – Dirk Geurs Nov 19 '13 at 21:27
-
Sorry, I just had not seen the check mark. – sunspots Nov 19 '13 at 21:33
2 Answers
0
Have a look at (take-nth n coll) function
(take-nth n coll)
Returns a lazy seq of every nth item in coll.
user=> (take-nth 2 (range 10))
(0 2 4 6 8)
It is not an exact match for your question but it is a good starting point for inspiration.
Of course, you can check the source code via:
(source take-nth)

Chiron
- 20,081
- 17
- 81
- 133
0
If you haven't figured it out by now, here is a function that does what you want.
(defn take-span
[start end step coll]
(take-nth step (take (- end start) (drop start coll))))
(take-span 1 4 2 '(:a :b :c :d :e :f :g :h))
Hope this helps!

Dirk Geurs
- 2,392
- 19
- 24