spec for a multi-arity function

890 views
Skip to first unread message

Peter Hull

unread,
Oct 5, 2017, 3:02:10 PM10/5/17
to Clojure
Is there any guidance on how to do the fdef for a function with more than one arity? As an example, this one which takes one or two arguments:

(defn report
 
"Report an error code, optionally with a message"
 
([errno] ...)
 
([errno msg] ...))

Could be:
(s/fdef report
       
:args (s/alt :brief (s/cat :errno integer?)
                     
:full (s/cat :errno integer? :msg string?)))

or:
(s/fdef report
       
:args (s/cat :errno integer? :msg (s/? string?)))


Some options make more sense than others, depending on the function. For example clojure.core/map is defined with five separate arities but I don't think it would be right to spec it as an alt with five alternatives, since they are all covered by "function followed by zero or more colls"

So, has a convention been established on how best to do it?

Alex Miller

unread,
Oct 5, 2017, 3:34:36 PM10/5/17
to Clojure


On Thursday, October 5, 2017 at 2:02:10 PM UTC-5, Peter Hull wrote:
Is there any guidance on how to do the fdef for a function with more than one arity? As an example, this one which takes one or two arguments:

The regex specs can cover multiple options via ?, *, etc.
 

(defn report
 
"Report an error code, optionally with a message"
 
([errno] ...)
 
([errno msg] ...))


So you want:

(s/fdef report
  :args (s/cat :errno int? :msg (s/? string?)))

Alex Miller

unread,
Oct 5, 2017, 3:36:41 PM10/5/17
to Clojure
I should also mention that the s/alt one is fine too, but in general I find receiving the same conformed map in either case but with keys either present or absent works better with all your typical Clojure destructuring etc so I prefer the s/? version.
Reply all
Reply to author
Forward
0 new messages