4Clojureを解いていく 解答メモ Easy編

4Clojureを解いていくだけの記事

解いたら更新

いつまで続くか不明

良い答え合ったら教えてください

19. Last Element

#(first  (reverse %))

20. Pnultimate Elements

(fn [seq] (first (rest (reverse seq))))

21. Nth Element

(fn [list num] (last (take (inc num) list)))

これは相当アホな書き方な自信がある

22. Count a Sequence

(fn [seq] (+ 1 (first (last (map-indexed vector seq)))))

23. Reverse a Sequence

(fn [coll] 
(letfn [(rev [coll] 
  (loop [num (- (count coll) 1) result []]
         (if (< num 0)
           result
           (recur (- num 1) (conj result (nth coll num)))
           )))]
  (if (set? coll)
    (rev (into [] coll))
    (rev coll)
    )
  ))

26. Fibonacci Sequence

(fn [n] (loop [num 2 fib '(1 1)] (if (= num n) fib (recur (+ num 1) (sort (conj fib (+ (last fib) (nth fib (- num 2)))))))))

遅延評価を使って書き直したい

(fn [n]
  (letfn [(fibs [] (map first (iterate (fn [[a b]] [b (+ b a)]) [1 1])))]
    (take n (fibs))))

こうか

27 Palindrome Detector

(fn [seq] (if (string? seq) (= seq (apply str (reverse seq))) (= seq (reverse seq))))

32 Duplicate Sequence

(fn [coll] (interleave coll coll))

34 Implement Range

(fn [start end] 
  (loop [num start 
         results []]
    (if (= num end)
      results
      (recur  (inc num) (conj results num)))))

39 Interleave Two Seqs

(fn [coll1 coll2]
  (loop [ind 0 results []]
    (if (or (= ind (count coll1)) (= ind (count coll2)))
      results
      (recur (inc ind) (conj results (nth coll1 ind) (nth coll2 ind))))))
      

40 Interpose a Seqs

(fn [n coll] 
  (loop [num 0 result []]
    (if (= num (dec (count coll)))
      (conj result (last coll))
      (recur (inc num) (conj result (nth coll num) n)))))

なぜかnthの引数の順番をいつも間違える

42 Factorial Fun

(fn [n]
  (loop [num n ans 1]
    (if (= num 0)
      ans
      (recur (dec num) (* ans num)))))

49 Split a sequence

(fn  [n coll]
                (loop [num 0 result [] seq coll]
                  (if (= num n)
                    (vector result seq)
                    (recur (inc num) (conj result (nth coll num)) (rest seq)))))

81 Set Intersection

#(set (filter %1 %2))