Saturday, 20 December 2008

99 Problems in Lisp (Part VI)

P19 Rotate a list N places to the left

(defn rotate [lst n]
(if (> n 0)
(take (count lst) (drop n (cycle lst)))
(take (count lst) (drop (- (count lst) (Math/abs n)) (cycle lst)))))

P20 Remove the kth element from the list

(defn remove-at [lst n]
(concat (take (dec n) lst) (drop n lst)))

P21 - Insert an element at a given position into a list

(defn insert-at [lst elt n]
(concat (take (dec n) lst) (list elt) (drop (dec n) lst)))