Fork me on GitHub
#clojure-spec
<
2018-11-04
>
roklenarcic15:11:57

I'm writing a macro where I want to turn the passed in symbol/keyword into a spec. How do I do that?

taylor15:11:02

s/get-spec if you’re trying to look up an existing spec by symbol/keyword

roklenarcic15:11:07

yeah but that doesn't work for predicates

roklenarcic15:11:14

like someone passes in string?

roklenarcic15:11:40

s/get-spec of course says that no such spec has been registered

borkdude15:11:19

Does creating a ::string spec work? @U08EKSQMS just made a PR to speculative for a lot of those

taylor15:11:12

it sounds like you want to check if the symbol resolves to a function (predicate), and then make a spec out of that function?

roklenarcic15:11:29

The thing is that it's a library so I don't know what people will be passing in.

roklenarcic15:11:34

Yes something like that

roklenarcic15:11:18

creating spec out of a symbol has the benefit of having that symbol show up in description of the spec failure

taylor15:11:37

this doesn’t really help, just an observation re: names/descriptions in failures:

(s/explain string? 0)
val: 0 fails predicate: :clojure.spec.alpha/unknown
=> nil
(s/explain (s/every string?) [0])
In: [0] val: 0 fails predicate: string?
=> nil

taylor15:11:20

(s/explain (s/spec string?) 0)
val: 0 fails predicate: string?
=> nil

taylor15:11:10

(defmacro ->spec [k]
  `(or (s/get-spec ~k) (s/spec ~k)))
(defn foo? [x] (= "foo" x))
=> #'?
(s/explain (->spec foo?) "foo")
Success!
=> nil
(s/explain (->spec foo?) "bar")
val: "bar" fails predicate: foo?
=> nil
(s/def ::foo #{"foo"})
=> :
(s/explain (->spec ::foo) "foo")
Success!
=> nil
(s/explain (->spec ::foo) "bar")
val: "bar" fails spec: : predicate: #{"foo"}
=> nil

taylor15:11:05

maybe something like that would work

roklenarcic15:11:27

cool I'll check it out

misha17:11:32

why do you need it in the first place? to have named things in explain's out? @U66G3SGP5

didibus23:11:05

I'm confused, sounds like you just want to call (s/def). It takes a keyword or symbol and registers a spec for it.