3 ms·
Last time I did a Clojure project, we've constrained the hell out of such maps with Clojure's Spec feature. Despite spending my last few years working with Com
by TeMPOraL 7y ago
Last time I did a Clojure project, we've constrained the hell out of such maps with Clojure's Spec feature.
Despite spending my last few years working with Common Lisp and a bit of Clojure, I've grown fond again of type constraints. Typing your data prevents a lot of silly and easy-to-make mistakes. Spec in Clojure is doubly useful, because specs can serve both as tests and generators. So after you define how your data is supposed to look like, you can make Clojure start pumping out randomly-generated examples, which you can then use to test your code.
(Note that typing maps with Spec doesn't mean they're inflexible, a priori structures. You just pin down what you know. In this case, you could define that a "person" needs a :name key, and can optionally have :admin?, :mod? and :nickname fields. If it also has some other fields, no harm done.)
- dustingetz 7y agoSpec can only say what is included in a map, it can't exclude. And the spec is late-bound by the caller. Different callers mandate different specs for the same entity. I see that you know this but I object to the wording "constrained".
- TeMPOraL 7y agoFair enough. It's entirely unlike constraining in statically-typed languages, but in practice it can still work as constraints if you verify the specs as pre/post conditions of your functions (for which Clojure has some nice syntactic goodies available by default). The way we've used it, it worked almost as if the maps were statically-typed, and it saved my bacon quite a few times.
- lsh 7y agoclojure.spec + orchestra for nicely integrated pre/post spec checking https://github.com/jeaye/orchestra https://github.com/jeaye/orchestra
- filoeleven 7y agoSpec alpha 2 supports closed maps: https://github.com/clojure/spec-alpha2/wiki/Differences-from-spec.alpha https://github.com/clojure/spec-alpha2/wiki/Differences-from...
- roenxi 7y agoSpec is supremely flexible, it isn't hard to enforce a map having a specific set of keys even without explicit support. (ns user (:use clojure.set) (:require [clojure.spec.alpha :as s])) (s/def ::map-closed #(-> % keys set (difference #{:a :b :c}) empty?)) (s/valid? ::map-closed {:a 1, :c 2}) => true (s/valid? ::map-closed {:a 1, :c 2, :e 3}) => false