Question

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

Was it helpful?

Solution

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!

OTHER TIPS

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top