Skip to content

Instantly share code, notes, and snippets.

@liquidz
Last active March 17, 2017 17:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liquidz/d82a4844ba35a197de33 to your computer and use it in GitHub Desktop.
Save liquidz/d82a4844ba35a197de33 to your computer and use it in GitHub Desktop.

core.typed: Annotation Patterns

core.typed dependencies: [org.clojure/core.typed "0.2.53"]

require: (require '[clojure.core.typed :as t])

Patterns

  • single param
(t/ann f1 [t/Str -> t/Str])
(defn f1
  [s]
  (str "hello " s))
  • no params
(t/ann f2 [-> t/Str])
(defn f2
  []
  "hello")
  • multiple params
(t/ann f3 [t/Num t/Num -> t/Num])
(defn f3
  [a b]
  (+ a b))
  • rest params
(t/ann f4 [t/Any * -> nil])
(defn f4
  [& x]
  (println x))
  • seq params
(t/ann f5 [(t/Seqable t/Num) -> t/Any])
(defn f5
  [ls]
  (map inc ls))
  
;; (f5 [1 2 3])
  • map params
(t/ann f6 [(t/Map t/Keyword t/Num) -> (t/U nil t/Num)])
(defn f6
  [m]
  (:n m))
  
;; (f6 {:n 10 :m 20})
  • high-order fn
(t/ann f7 [(t/IFn [t/Num -> t/Num]) (t/Seqable t/Num) -> t/Num])
(defn f7
  [f ls]
  (apply + (map f ls)))
  
;; (f7 inc [1 2 3])
  • multiple arity
(t/ann f8 (t/IFn [t/Num -> t/Num] [t/Num t/Num -> t/Num]))
(defn f8
  ([a] (f8 a 1))
  ([a b] (+ a b)))
  
;; (f8 1)
;; (f8 1 2)
  • union
(t/ann f9 [(t/U t/Num t/Str) -> t/Str])
(defn f9
  [x]
  (if (string? x) x (str x)))
  
;; (f9 1)
;; (f9 "1")
  • keyword params
(t/ann f10 [& :optional {:a t/Num, :b t/Num} -> t/Num])
(defn f10
  [& {:keys [a b] :or {a 1, b 2}}]
  (+ a b))
  
;; (f10 :a 10)
;; (f10 :b 20)
;; (f10 :a 10 :b 20)
  • java instance method
(t/ann f11 [t/Str -> t/Num])
(defn f11
  [^String s]
  (.length s))
  
;; (f11 "hello")
  • use unchecked vars
(require '[clojure.java.io :as io])

(t/ann f12 [String -> java.io.File])
(t/ann ^:no-check clojure.java.io/file [String -> java.io.File])
(defn f12
  [path]
  (t/let [real-path :- t/Str (str "/path/to/" path)]
    (io/file real-path)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment