99 Clojure Problems (15-18)

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 '()] 
                (= (count output) n) 
                (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) 
        (= 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)))))

2 Replies to “99 Clojure Problems (15-18)”

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

Leave a Reply

Your email address will not be published. Required fields are marked *

jon.com.org.net is using WP-Gravatar