Created
January 3, 2010 19:59
-
-
Save hickst/268109 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; the missing drop-nth, versions of which, similar to this, have been floating around the Clojure forum: | |
;; | |
(defn drop-nth [n coll] | |
(lazy-seq | |
(when-let [xs (seq coll)] | |
(concat (take (dec n) xs) (drop-nth n (drop n xs))) | |
) | |
) | |
) | |
;; A sub sequence function based on pretending the sequence is indexed (ala 'subvec'). | |
;; Authors: Tom Hicks and Tim Pratley. | |
;; | |
(defn indexed-subseq | |
"Returns a lazy sequence of the items in the given sequence from | |
start (inclusive) to end (exclusive). If end is not supplied, | |
defaults to (count sequence)." | |
([coll start] | |
(when (not (neg? start)) | |
(drop start coll)) | |
) | |
([coll start end] | |
(when (and (not (neg? start)) (<= start end)) | |
(take (- end start) (drop start coll))) | |
) | |
) | |
;; some tests | |
; (def v (vec (range 1 8))) | |
; (indexed-subseq v 4) | |
; = (5 6 7) | |
; (map #(indexed-subseq v %) (range 8)) | |
; = ((1 2 3 4 5 6 7) (2 3 4 5 6 7) (3 4 5 6 7) (4 5 6 7) (5 6 7) (6 7) (7) ()) | |
; (map #(indexed-subseq v %1 %2) (repeat 0) (range 9)) | |
; = (() (1) (1 2) (1 2 3) (1 2 3 4) (1 2 3 4 5) (1 2 3 4 5 6) (1 2 3 4 5 6 7) (1 2 3 4 5 6 7)) | |
; (indexed-subseq [0 1 2 3 4] 1 3) | |
; = (1 2) | |
; (indexed-subseq [0 1 2 3 4] -5 3) | |
; = nil | |
; (indexed-subseq [0 1 2 3 4] 4 3) | |
; = nil | |
; (indexed-subseq [0 1 2 3 4] 2) | |
; = (2 3 4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment