clojure.spec & protocol fn

1209 views
Skip to first unread message

Claudius Nicolae

unread,
Jun 5, 2016, 12:57:10 PM6/5/16
to Clojure
It seems that protocol fns don't participate in s/fdef specfications. It would be nice they were. Sample:

    (ns sample
      (:require [clojure.spec :as s]))
    
    (s/instrument-all)
    
    ;; Spec a fn
    
    (s/fdef f
      :args (s/cat :i integer?)
      :ret integer?)
    
    (defn f [i] i)
    
    (f "1") ; will fail
    
    ;; Spec a fn of a protocol
    
    (defprotocol P
      (g [p i]))
    
    (s/fdef g
      :args (s/cat :p (partial satisfies? P)
                   :i integer?)
      :ret integer?)
    
    (defrecord R []
      P
      (g [_ i] i))
    
    (g (->R) "2") ; will pass

Kevin Downey

unread,
Jun 5, 2016, 2:23:10 PM6/5/16
to clo...@googlegroups.com
http://dev.clojure.org/jira/browse/CLJ-1941 has some discussion about
places where instrumenting won't work.
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clo...@googlegroups.com
> Note that posts from new members are moderated - please be patient with
> your first post.
> To unsubscribe from this group, send email to
> clojure+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
> ---
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to clojure+u...@googlegroups.com
> <mailto:clojure+u...@googlegroups.com>.
> For more options, visit https://groups.google.com/d/optout.


--
And what is good, Phaedrus,
And what is not good—
Need we ask anyone to tell us these things?

Vjeran Marcinko

unread,
Jun 6, 2016, 3:53:55 PM6/6/16
to Clojure
On Sunday, June 5, 2016 at 8:23:10 PM UTC+2, red...@gmail.com wrote:
http://dev.clojure.org/jira/browse/CLJ-1941 has some discussion about
places where instrumenting won't work.


Does this mean that this is a bug or something crucial related to protocol design is preventing this ever being implemented?

-Vjeran

Brandon Bloom

unread,
Jun 6, 2016, 10:23:04 PM6/6/16
to Clojure
Just guessing from past experience in the Clojure internals:

Instrumenting protocol methods it likely possible, but unlikely to be worth the effort.

There are already a bunch of places where protocol functions are different. The accepted convention is to always wrap a protocol method with a normal function to recover the benefits. The pattern usually looks like:

(defprotocol P
  (-foo [x y z]))

(defn foo [x y z]
  (-foo x y z))

Put your spec on foo, not -foo.

This tends to be good practice anyway because you have a place to wrap global behavior around -foo.
Reply all
Reply to author
Forward
0 new messages