Skip to content

Instantly share code, notes, and snippets.

@wildwestrom
Created November 9, 2021 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wildwestrom/9568e9c659d30a2a663a9a0a8235a6b9 to your computer and use it in GitHub Desktop.
Save wildwestrom/9568e9c659d30a2a663a9a0a8235a6b9 to your computer and use it in GitHub Desktop.
Clojure `any?`
(ns user
(:require [clojure.test :refer [are deftest]]
[clojure.test.check.clojure-test :refer [defspec]]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop])
(:refer-clojure :exclude [any?]))
(comment
"Clojure's `any? ` function seems to just return `true ` always."
(defn any?
"Returns true given any argument."
{:tag Boolean
:added "1.9"}
[x] true)
"Contrast this with `not-any? `."
(def
^{:tag Boolean
:doc "Returns false if (pred x) is logical true for any x in coll,
else true."
:arglists '([pred coll])
:added "1.0"}
not-any? (comp not some))
"I believe `any? ` should take two arguments and return `true ` if any predicate is `true `."
(def
^{:tag Boolean
:doc "Returns true if (pred x) is logical true for any x in coll,
else false."
:arglists '([pred coll])
:added "1.9"}
any? (comp boolean some))
"Credit to Kofrasa on ClojureDocs."
"https://clojuredocs.org/clojure.core/any_q"
"https://clojuredocs.org/u/kofrasa"
)
;; This demonstrates the mistake in implementation.
(deftest clojure-any
(are [x y] (= ((comp boolean some) true? x) (clojure.core/any? y))
[true] true
[false] false ;; this fails
[true true] true
[false true] true
[false false] false ;; so does this
))
(def
^{:tag Boolean
:doc "Returns true if (pred x) is logical true for any x in coll,
else false."
:arglists '([pred coll])
:added "1.9"}
any? (comp boolean some))
;; Here is the correct implementation.
(defspec correct-any 1000
(prop/for-all [v (gen/such-that not-empty (gen/vector gen/boolean))]
(= ((comp boolean some) true? v)
(any? true? v)
(not (not-any? true? v)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment