4Clojure-Part2

Factorial Fun

(fn [n]
  (loop [n n f 1]
    (if (zero? n)
      f
      (recur (dec n)
             (* f n)))))

そのまんま。

Interpose a Sequence

(fn [x coll]
  (loop [coll coll s ()]                                   
    (if (empty? coll)
      (rest (reverse s))
      (recur (rest coll)
             (cons (first coll) (cons x s))
             ))))

出力するときにいじるのはちょっとかっこ悪い・・・

Interleave Two Seqs

(fn [coll coll2]
  (loop [coll coll coll2 coll2 out ()]
    (if (or (empty? coll) (empty? coll2)) 
      (reverse out)
      (recur (rest coll)
             (rest coll2) 
             (cons (first coll2) (cons (first coll) out) )
             ))))

うーん・・・長い。

(fn [coll coll2]
  (letfn [(my-interpose-c [x y] (cons x (cons y ())))]
    (flatten (map my-interpose-c coll coll2))))

こうか?