Skip to content

Instantly share code, notes, and snippets.

@danmidwood
Created March 18, 2013 01:36
Show Gist options
  • Save danmidwood/5184452 to your computer and use it in GitHub Desktop.
Save danmidwood/5184452 to your computer and use it in GitHub Desktop.
Translation of SICP make-rat, denom and numer operations to Clojure with the addition of Typed Clojure to define a "SicpRatio" type as an alias to a vector of size 2
(ns complex-clojure.core
(:require [clojure.core.typed :as t])
(:use [clojure.core.typed :only [AnyInteger]]))
(t/def-alias SicpRatio (Vector* AnyInteger AnyInteger))
(t/ann make-rat [AnyInteger AnyInteger -> SicpRatio])
(defn make-rat [numer denom] [numer denom])
(t/ann denom [SicpRatio -> AnyInteger])
(defn denom [[_ denom]] denom)
(t/ann numer [SicpRatio -> AnyInteger])
(defn numer [[numer _]] numer)
;; cf is abbreviated from check form. It can be used to check our types
(t/cf (make-rat 1 5))
;; complex-clojure.core/SicpRatio
(comment
;; This fails the check because 1.1 is not an integer
(t/cf (make-rat 1.1 5)))
(t/cf (numer (make-rat 1 5)))
;; (U java.lang.Long java.lang.Integer java.math.BigInteger java.lang.Byte java.lang.Short clojure.lang.BigInt)
;; AnyInteger is an alias for this Union
;; We don't need to construct with make-rat, anything that conforms to the type will do
(t/cf (numer [1 5]))
;; But our vector still needs to be the correct size
(comment
(t/cf (numer [1 5 10]))
;; Errors with
Actual type
[(Value 1) (Value 5) (Value 10)]
is not a subtype of Expected type
complex-clojure.core/SicpRatio clojure.core.typed/type-error (subtype.clj:24)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment