Skip to content

Instantly share code, notes, and snippets.

@lcs-felix
Last active August 8, 2020 15:57
Show Gist options
  • Save lcs-felix/d70074e1aa31e8652cc5d0ab41eff502 to your computer and use it in GitHub Desktop.
Save lcs-felix/d70074e1aa31e8652cc5d0ab41eff502 to your computer and use it in GitHub Desktop.
(defn abs [x]
(if (> x 0) x (* -1 x)))
(defn gcd
[a b]
(if (= b 0)
(abs a)
(recur b (mod a b))))
(s/def ::gcd-args (s/cat :a int? :b int?))
(s/fdef gcd
:args ::gcd-args
:ret nat-int?
:fn (s/or
:zero #(and (zero? (-> % :args :a)) (zero? (:ret %)))
:greater-than-zero #(and (= (mod (-> % :args :a) (:ret %)) 0)
(= (mod (-> % :args :b) (:ret %)) 0))))
(s/exercise-fn `gcd)
(->> (test/check `gcd) test/summarize-results)
(ns clojure-tests.spec-demo
(require '[clojure.spec.alpha :as s]
'[clojure.spec.test.alpha :as test]
'[clojure.string :as str]))
(defn my-index-of
[source search]
(str/index-of source search))
(s/def ::index-of-args (s/cat :source string? :search string?))
(s/fdef my-index-of
:args ::index-of-args
:ret (s/nilable nat-int?)
:fn (s/or
:not-found #(nil? (:ret %))
:found (s/and
#(str/includes? (-> % :args :source) (-> % :args :search))
#(<= (:ret %) (-> % :args :source count)))))
(s/exercise-fn `my-index-of 15)
;; ([("" "") 0]
;; [("" "") 0]
;; [("S" "") 0]
;; [("sca" "") 0]
;; [("XAy" "KyO") nil]
;; [("07d" "9prw") nil]
;; [("9P6L6" "6Rm") nil]
;; [("s" "") 0]
;; [("rr7mx" "xFJV7n") nil]
;; [("HvFt17FBM" "LF1sc") nil]
;; [("MQ7fr2" "") 0]
;; [("5" "4") nil]
;; [("" "hYTPhXvwdg1k") nil]
;; [("rK6gOz1je" "RfQQ0c") nil]
;; [("ikVkh8m0" "4aOy86yX") nil])
(->> (test/check `my-index-of) test/summarize-results)
;; {:sym clojure-tests.spec-demo/my-index-of}
;; => {:total 1, :check-passed 1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment