Skip to content

Instantly share code, notes, and snippets.

@Bill Bill/part1.clj
Last active Mar 3, 2017

Embed
What would you like to do?
Clojure Collection Processing In Context: Part I: Eager to Process
;
; Clojure Collection Processing In Context: Part I: Eager to Process
; © 2017, by Bill Burcham
;
; Slides at: https://docs.google.com/presentation/d/1wKcTN5-f00ZCKk_LpUG5GIorh89AImmuxvG7MiGiF1c
;
(ns ccpic.part1)
(use 'clojure.repl)
; command-dot to collapse section
; #1a - stutter #1
(defn stutter [c]
(when (seq c)
(let [x (first c)]
(conj (stutter (rest c)) x x))))
; #1b - trying it out
(stutter [1 2 3])
(stutter [])
(stutter nil)
(= (stutter [1 2 3]) '(1 1 2 2 3 3))
; #2a - recursive calls
(stutter [1 2 3])
(rest [1 2 3])
(stutter '(2 3))
(rest '(2 3))
(stutter '(3))
(rest '(3))
(stutter ())
; #2b - expanding exprs
(conj (stutter (rest '(3))) 3 3)
(rest '(3))
;(conj (stutter ()) 3 3)
(stutter ())
;(conj nil 3 3)
(conj nil 3 3)
; #3a - what kind of collection is produced?
(type (conj nil 3 3))
(type (stutter [1 2 3]))
; #3b - what conj usually does
(conj '(1) 2)
(conj [1] 2)
(conj {:a 1} {:b 2})
(conj #{1} 2)
; #4 - doc
(doc stutter)
; # 6 - trying a bigger collection
1e1
(stutter (range 1e1))
(dec 2e1)
(nth (stutter (range 1e1)) (dec 2e1))
1e4
(nth (stutter (range 1e4)) (dec 2e4))
; #7 - first try at recur
(defn stutter
[c]
(when-let [s (seq c)]
(let [x (first s)]
(conj (recur (rest s)) x x))))
; #8 - tail recursive
(defn stutter [c]
(
(fn inner [c accum]
(if-let [s (seq c)]
(let [x (first s)]
(recur (rest s) (conj accum x x)))
accum))
c []))
(nth (stutter (range 1e4)) (dec 2e4))
; #9 - using loop
(defn stutter [c]
(loop [c c
accum []]
(if-let [s (seq c)]
(let [x (first s)]
(recur (rest s) (conj accum x x)))
accum)))
(nth (stutter (range 1e4)) (dec 2e4))
; was our choice of accumulator (vector) arbitrary?
(defn stutter [c]
(loop [c c
accum ()]
(if-let [s (seq c)]
(let [x (first s)]
(recur (rest s) (conj accum x x)))
accum)))
(stutter [1 2 3])
(conj [1] 2)
(conj '(1) 2)
; #10 - documenting and cleaning up
(defn stutter
"Given a finite Seqable c, produces a vector. Each element of the source sequence is repeated (twice) in the output list, e.g. (stutter [:a :b]) evaluates to (:a :a :b :b)"
[c]
(loop [c c
accum []]
(if-let [s (seq c)]
(let [x (first s)]
(recur (rest s) (conj accum x x)))
accum)))
(doc stutter)
; end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.