Skip to content

Instantly share code, notes, and snippets.

@shepmaster
Created May 4, 2014 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shepmaster/234a90b439e0585f0ec5 to your computer and use it in GitHub Desktop.
Save shepmaster/234a90b439e0585f0ec5 to your computer and use it in GitHub Desktop.
Picking between Cows and Pigs
(ns typed.core
(:require [clojure.core.typed :as t :refer [ann ann-form def-alias declare-names]]))
(def-alias Cow '{:type ':cow})
(def-alias Pig '{:type ':pig})
(def-alias Animal (U Cow Pig))
(t/ann in-the-barn '[Animal Animal *])
(def in-the-barn [{:type :cow} {:type :pig}])
;; Could cow? have automatic annotations, as it comes from core.typed?
(t/ann cow? [Any -> Boolean
;; Doesn't work
;;:filters {:then (is Cow 0)
;; :else (is Pig 0)}
])
(def cow? (t/pred Cow))
(t/ann cow-moo [Cow -> nil])
(defn cow-moo [cow]
(println "Moo"))
(t/ann pig-oink [Pig -> nil])
(defn pig-oink [pig]
(println "Oink"))
(let [a (first in-the-barn)]
(if (cow? a)
(cow-moo a)
(pig-oink a)))
First error:
Type Error (NO_SOURCE_FILE:29:5) Type mismatch:
Expected: Cow
Actual: (U typed.core/Cow typed.core/Pig)
in: (cow-moo a)
Type Error (NO_SOURCE_FILE:30:5) Type mismatch:
Expected: Pig
Actual: (U typed.core/Cow typed.core/Pig)
in: (pig-oink a)
Type Error (NO_SOURCE_FILE:17:1) Type mismatch:
Expected: (Fn [Any -> java.lang.Boolean :filters {:then (is Cow 0), :else (is Pig 0)}])
Actual: (Fn [Any -> Boolean :filters {:then (is nil 0), :else (! nil 0)}])
in: (def cow? (clojure.core.typed/pred* (quote Cow) (quote typed.core) (fn* ([arg2920] (clojure.lang.RT/booleanCast ((clojure.core.typed.current-impl/hmap-c? :mandatory {:type (fn* ([G__2921] (clojure.la\
ng.Util/identical (quote :cow) G__2921)))} :optional {} :absent-keys #{} :complete? false) arg2920))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment