#:g1: clojureでL-99 (P17 指定した位置でリストを分割)

Posted 2008-10-05 08:18:00 GMT

-(http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html)
ありあわせの関数を使っちゃいけないということなので自前で処理しましたが、take、drop、take-while等々あるのでそれを使えば簡単に書けます。

(defn 
  #^{:doc "P17 (*) Split a list into two parts; the length of the first part is given."
     :test (do (test= (split [] 3) [[] []])
               (test= (split '(a b c d e f g h i k) 3)
                      '((a b c) (d e f g h i k)))
               (test= (split '(a b c d e f g h i k) -3)
                      '(()(a b c d e f g h i k)))
               (test= (split '(a b c d e f g h i k) 100)
                      '((a b c d e f g h i k) () ))) }
; -----
  split
; -----
  ([coll pos]
     (let [len (count coll)]
       (cond 
        (<= len pos) (list coll [])
        (>= 0 pos) (list [] coll)
        :else
        (loop [coll coll, cnt pos, head [] ]
          (if (or (empty? coll) (zero? cnt))
            (list (reverse head) coll)
            (recur (rest coll)
                   (+ -1 cnt)
                   (cons (first coll) head))))))))

comments powered by Disqus