Skip to content

Instantly share code, notes, and snippets.

@tie-rack
Last active May 18, 2020 23:47
Show Gist options
  • Save tie-rack/10c700ce1448bfc300e8278e6a47bb04 to your computer and use it in GitHub Desktop.
Save tie-rack/10c700ce1448bfc300e8278e6a47bb04 to your computer and use it in GitHub Desktop.
(ns collection-predicates)
(defmacro report
"A macro that takes Clojure code then prints the code and its results."
[title & forms]
(concat
`(do
(printf "=== %s ===\n" ~title))
(map (fn [form]
(if (= 'skip (first form))
(let [[_ skipped-form output] form]
`(printf "%s ;;=> %s\n" '~skipped-form ~output))
`(let [result# ~form]
(printf "%s ;;=> %s\n" '~form (pr-str result#)))))
forms)
'((println))))
(println "== Testing items in collections in Clojure ==")
(println)
(println "A Tara Talk(tm) by Chris Shea")
(println)
(println)
(report
"other fns used in this demo"
(even? 2)
(even? 3)
(neg? 1)
(neg? 0)
(neg? -1)
(skip (range) "(0 1 2 3 4 ...)"))
(report
"not-every?"
(not-every? even? [2 4 6])
(not-every? even? [2 4 5])
(not-every? even? [1 3 5]))
(report
"every?"
(every? even? [2 4 6])
(every? even? [2 4 5])
(every? even? [1 3 5]))
(report
"not-any?"
(not-any? even? [2 4 6])
(not-any? even? [2 4 5])
(not-any? even? [1 3 5]))
(report
"any?"
(any? [])
(any? true)
(any? false)
(any? nil))
;; this was just me being salty about how `any?` is not the opposite
;; of `not-any?`. `any?` is a function of one argument that always
;; returns true. You do not need it.
(report
"some"
(some even? [2 4 6])
(some even? [2 4 5])
(some even? [1 3 5]))
;; `some` is a close approximate of the opposite of `not-any?`.
(report
"empty"
(some even? [])
(not-any? even? [])
(every? even? [])
(not-every? even? []))
(report
"infinite"
(some even? (range))
(not-every? even? (range))
(skip (not-any? neg? (range)) "... ~~hangs forever~~"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment