Skip to content

Instantly share code, notes, and snippets.

@fogus
Created August 26, 2010 15:17
Show Gist options
  • Save fogus/551579 to your computer and use it in GitHub Desktop.
Save fogus/551579 to your computer and use it in GitHub Desktop.
(def sqr-8bit-contract
(contract atari-constraints
"Defines the constraints for Atari 2600 squaring"
[n] [(< n 16) integer? pos? => (< % 256)]))
(def sqr-8bit
(with-constraints
constrained-sqr
sqr-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)
(def sqr-8bit-contract
(contract atari-constraints
"Defines the constraints for Atari 2600 squaring"
[_] [number? => (< % 256)]))
(def sqr-8bit
(with-constraints
constrained-sqr
sqr-8bit-contract))
(sqr-8bit 5)
;=> 25
(sqr-8bit 0)
; java.lang.AssertionError:
; Assert failed: (not= 0 num)
(defconstrainedfn sqr
"Squares a number"
[n] [(number? n) (not= 0 n) ;; requires/domain
=>
(pos? %) (number? %)] ;; ensures/range
(* n n))
(defconstrainedfn doubler
"Defines a function that doubles its input."
([n] [(number? n) => (= (* 2 n) %)]
(* 2 n))
([x y] [(every? number? [x y])
=>
(number? %)
(= (* 2 (+ x y)) %)]
(* 2 (+ x y))))
(defcontract sqr-contract
"Defines the constraints for squaring"
[n] [number? (not= 0 n) => pos? number?])
(provide-contracts
[sqr "Constraints for squaring"
[x] [number? (not= 0 x) => number? pos?]])
(sqr 0)
; java.lang.AssertionError:
; Assert failed: (not= 0 n)
(defcontract sqr-contract
"Defines the constraints on squaring."
[n] [number? (not= 0 n) => pos? number?])
(sqr 0)
;=> 0
(provide-contracts
[sqr "Apply the contract for squaring"
sqr-contract])
(sqr 0)
; java.lang.AssertionError:
; Assert failed: (not= 0 n)
(def sqr-contract
(contract sqr-constraints
"Defines the constraints for squaring"
[n] [number? (not= 0 n) => pos? number?]))
(defconstrainedfn sqr
"Squares a number"
[n] [number? (not= 0 n) => pos? number?]
(* n n))
(use '[fogus.me.trammel
:only [provide-contracts]])
(defn sqr [n] (* n n))
(sqr 10)
;=> 100
(sqr 0)
;=> 0
(provide-contracts
[sqr "Constraints for squaring"
[x] [number? (not= 0 x) => number? pos?]])
(sqr 10)
;=> 100
(sqr 0)
; java.lang.AssertionError:
; Assert failed: (not= 0 x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment