Not much to say about this batch. I burned through these too fast to learn a lot. I guess I did learn about clojure’s drop function, but most of the rest of these are just tweaks of earlier problems.
; P15 (**) Duplicate the elements of a list a given number of times. (defn duplicateN [n l] (mapcat (fn [a] (loop [output '()] (if (= (count output) n) output (recur (cons a output))))) l)) ; P16 (**) Drop every Nth element from a list. (comment "clojure's (drop n list) throws away the first n items in a list and returns the list") (defn s99_drop [n l] (loop [[head & tail] l c 1 output '()] (if (nil? head) (reverse output) (if (= c n) (recur tail 1 output) (recur tail (inc c) (cons head output)))))) ; P17 (*) Split a list into two parts; the length of the first part is given. (defn split [n l] (loop [c 0 [head & tail] l output '()] (if (< c (dec n)) (recur (inc c) tail (cons head output)) (list (reverse (cons head output)) tail)))) ; P18 (**) Extract a slice from a list. (comment "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.") (defn slice [i k l] (loop [remaining (drop i l) current i output '()] (if (= current k) (reverse output) (recur (rest remaining) (inc current) (cons (first remaining) output)))))
did you consider:
(defn slice [i k l] (take (- k i) (drop i l)))
for your slice function?
No, I didn’t, actually… I think it was a combination of ignorance and thinking of the problem from a “recreate it myself” standpoint. Not sure why I used the drop, though… It may have been late.