Skip to content

Instantly share code, notes, and snippets.

@lagenorhynque
Last active September 22, 2016 23:38
Show Gist options
  • Save lagenorhynque/a833052a33d4db38ccae2db24c347583 to your computer and use it in GitHub Desktop.
Save lagenorhynque/a833052a33d4db38ccae2db24c347583 to your computer and use it in GitHub Desktop.
;;;; cf. http://riktor.hatenablog.com/entry/2012/07/25/001118
(first '(1 2 3))
(first '((1 2 3) 4 5 6))
(rest '(1 2 3))
(rest '(1 2 (3 4 5)))
(cons 1 '(2 3))
(cons '(1 2 3) '((4 5 6)))
(cons 1 nil)
(rest '(1))
(rest nil)
(identical? nil ())
(rest ())
(defn my-nth-rest [n coll]
(if (or (empty? coll) (zero? n))
coll
(recur (dec n) (rest coll))))
(defn my-map [f coll]
(if (empty? coll)
()
(cons (f (first coll))
(my-map f (rest coll)))))
(my-map (fn [x] (* x 2)) '(1 2 3))
(my-map (fn [x] (- x 1)) '(1 2 3))
(defn my-map-tailrec [f coll]
(letfn [(helper [coll acc]
(if (empty? coll)
(reverse acc)
(recur (rest coll)
(cons (f (first coll)) acc))))]
(helper coll ())))
(defn my-append [coll1 coll2]
(if (empty? coll1)
coll2
(cons (first coll1)
(my-append (rest coll1) coll2))))
(defn my-append-tailrec [coll1 coll2]
(letfn [(rec [coll acc]
(if (empty? coll)
(concat (reverse acc) coll2)
(recur (rest coll)
(cons (first coll) acc))))]
(rec coll1 ())))
(defn my-append-concat [coll1 coll2]
(concat coll1 coll2))
(defn my-append-splicing [coll1 coll2]
`(~@coll1 ~@coll2))
(defn my-append-cps [coll1 coll2]
(letfn [(rec [coll cont]
(if (empty? coll)
(cont coll2)
(recur (rest coll)
(fn [x] (cont (cons (first coll) x))))))]
(rec coll1 identity)))
(defn my-reverse [coll]
(letfn [(rec [coll acc]
(if (empty? coll)
acc
(recur (rest coll)
(cons (first coll) acc))))]
(rec coll ())))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment