Tuesday, February 11, 2014

99 Clojure Problems – 20: Remove the Kth Element from a List

Return the list and the removed element in a tuple. Elements are numbered from 0.

Example:

(deftest p20-remove-at
  (is (= '((a c d) b) (remove-at 1 '(a b c d)))))

Solution:

A quick one: Reuse split from problem 17 to cut the input sequence into two parts. I called them head and tail, which is not quite accurate as head usually refers to the first element of a sequence only. You can then concatenate the head part and the tail part again into a single sequence. Calling rest on the tail before concatenating removes the right element. Calling first on the tail allows you to return the removed element as required (Source).

Read more about this series.

No comments: