Friday, February 07, 2014

99 Clojure Problems – 18: Extract a Slice from a List

Given two indices, I and K, the slice is the list containing the elements from and including the Ith element up to but not including the Kth element of the original list. Start counting the elements with 0.

Example

(deftest p18-slice
  (is (= '(d e f g) (slice 3 7 '(a b c d e f g h i j k)))))

Solution

If we drop the first I elements we get a lazy sequence starting with the Ith element (because we count starting with 0). If we then take the difference between K and I and remove as many elements from our sequence we obtain the desired slice (Source).

Read more about this series.

No comments: