Skip to content

Instantly share code, notes, and snippets.

@wildwestrom
Created Nov 9, 2021
Embed
What would you like to do?
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