As you saw in the description of defconstrainedfn core.contracts allows you to create functions with a localized and dependent contract. However, there may be circumstances where the separation of contract and constrained function is preferred. Take for example, a simple slope function:
(defn sqr [n] (* n n))
(def sqr-contract(contract sqr-constraints"Defines the constraints for squaring"[n] [number? (not= 0 n) => pos? number?]))
(def constrained-sqr(with-constraintssqrsqr-contract))(constrained-sqr 5);=> 25(constrained-sqr -5);=> 25(constrained-sqr 0); java.lang.AssertionError: Assert failed:
(not= 0 num)(constrained-sqr :a); java.lang.AssertionError: Assert failed:
(number? num)
(def sqr-8bit-contract(contract atari-constraints"Defines the constraints for Atari 2600 sqr"[_] [number? => (< % 256)]))(def sqr-8bit(with-constraintsconstrained-sqrsqr-8bit-contract))(sqr-8bit 5);=> 25(sqr-8bit 0); java.lang.AssertionError:; Assert failed: (not= 0 num)
(sqr-8bit 100); java.lang.AssertionError:; Assert failed: (< % 256)
(def sqr-8bit-contract(contract atari-constraints"Defines the constraints for Atari 2600 sqr"[n] [(< n 16) integer? pos? => (< % 256)]))(def sqr-8bit(with-constraintsconstrained-sqrsqr-8bit-contract))(sqr-8bit 15);=> 225(sqr-8bit -5); java.lang.AssertionError:; Assert failed: (pos? n)(sqr-8bit 15.9687194); java.lang.AssertionError:; Assert failed: (integer? n)(sqr-8bit 16); java.lang.AssertionError:; Assert failed: (< n 16)
Can you improve this documentation?Edit on GitHub
cljdoc is a website building & hosting documentation for Clojure/Script libraries
× close