Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (ns for-repl.core-typed-examples
- (:require [clojure.core.typed :refer [ann
- ann-record
- ann-datatype
- ann-form
- defalias
- HMap
- Map
- Any
- All
- U
- Seq
- Keyword
- Fn]]
- [clojure.core.match :refer [match]]))
- (defalias Failure (All [a] (HMap :mandatory {:exception a} :complete? true)))
- (defalias Success (All [a] (HMap :mandatory {:result a} :complete? true)))
- (ann as-success (All [a] [a -> Success]))
- (defn ^:no-check as-success [value]
- (ann-form {:result value} Success))
- (ann as-failure (All [a] [a -> Failure]))
- (defn ^:no-check as-failure [exception]
- (ann-form {:exception exception} Failure))
- (defalias Try (U Failure Success))
- (ann parse-long [String -> Try])
- (defn parse-long [str]
- (try
- (as-success (Long/parseLong str))
- (catch NumberFormatException e
- (as-failure e))))
- (ann-record Human [name :- String weight :- Long])
- (defrecord Human [name weight])
- (ann human [String Long -> Human])
- (defn human [name weight]
- (Human. name weight))
- (defalias Args (U (Seq String) nil))
- (ann args->human [Args -> Try])
- (defn ^:no-check args->human [args]
- (as-> {:args "Wrong number of arguments"
- :name-presence "Name there must be"
- :weight-presence "Weight there must be"
- :weight-format "Weight must be Long"}
- errors
- (match (vec args)
- [name weight]
- (match [(parse-long weight)]
- [^Try {:result v}] (as-success (human name v))
- [^Try {:exception _}] (as-failure (select-keys errors [:weight-format])))
- [] (as-failure (select-keys errors [:args :name-presence :weight-presence]))
- [_] (as-failure (select-keys errors [:args :weight-presence]))
- :else (as-failure (select-keys errors [:args])))))
- (defalias ExData (U nil (Map Any Any)))
- (ann log-error [ExData -> nil])
- (defn log-error [errors]
- (some-> errors println))
- (ann print-human [Human -> nil])
- (defn print-human [human]
- (println human))
- (ann check [String * -> nil])
- (defn check [& args]
- (match [(args->human args)]
- [^Try {:result v}] (print-human v)
- [^Try {:exception e}] (-> e println)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement