#:g1: clojureでL-99 (P18 範囲切り出し)

Posted 2008-10-06 12:31:00 GMT

-(http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html)
clojureには標準でsubseqがあります。

(defn
  #^{:doc "P18 (**) Extract a slice from a list."
     :test (do (test= (slice [] 3 7) [])
               (test= (slice '(a b c d e f g h i k) 3 7)
                      '(c d e f g))
               (test= (slice '(a b c d e f g h i k) -3 7)
                      (slice '(a b c d e f g h i k) 1 7))
               (test= (slice '(a b c d e f g h i k) -3 100)
                      '(a b c d e f g h i k))) }
; -----
  slice
; -----
  ([coll start end]
     (if (empty? coll)
       []
       (let [len (count coll), start (max start 1), end (min end len)]
         (loop [coll coll, pos 1, acc [] ]
           (if (or (empty? coll) (< end pos))
             (reverse acc)
             (recur (rest coll)
                    (+ 1 pos)
                    (if (<= start pos end)
                      (cons (first coll)
                            acc)
                      acc))))))))

comments powered by Disqus