Fork me on GitHub
#malli
<
2023-04-14
>
steveb8n00:04:24

Q: is there a way to apply a defn schema to an anonymous fn? I have a higher order fn that accepts fn args and I want to apply a schema to the incoming fns (which can be anon)

steveb8n00:04:15

I don’t think instrumenting the HOF is applied to the incoming fn args

steveb8n02:04:55

same for return values which are fns from a HOF. I guess that anon fns cannot be instrumented because instrumentation requires a fn var?

ikitommi12:04:44

you can instrument functions too.

ikitommi12:04:57

from https://github.com/metosin/malli/blob/master/docs/function-schemas.md:

(def pow
  (m/-instrument
    {:schema [:=> [:cat :int] [:int {:max 6}]]}
    (fn [x] (* x x))))

ikitommi13:04:18

but, in Clojure, there is no way to check the function arities, argument or return types - but we can use generative testing to brute force the inputs to see if they are of correct type.

ikitommi13:04:58

(def =>plus 
  (m/schema
    [:=> [:cat :int :int] :int] 
    {::m/function-checker mg/function-checker}))

(m/validate =>plus plus)
; => true

(m/validate =>plus str)
; => false

ikitommi13:04:15

(m/explain =>plus str)
;{:schema [:=> [:cat :int :int] :int],
; :value #object[clojure.core$str],
; :errors ({:path [],
;           :in [],
;           :schema [:=> [:cat :int :int] :int],
;           :value #object[clojure.core$str],
;           :check {:total-nodes-visited 0,
;                   :depth 0,
;                   :pass? false,
;                   :result false,
;                   :result-data nil,
;                   :time-shrinking-ms 1,
;                   :smallest [(0 0)],
;                   :malli.generator/explain-output {:schema :int,
;                                                    :value "00",
;                                                    :errors ({:path []
;                                                              :in []
;                                                              :schema :int
;                                                              :value "00"})}}})}

ikitommi13:04:58

also, not sure if there is an option to enable the generative function testing into or malli.instrument. If not, PR most welcome!

ikitommi13:04:28

side-note: only non-side effecting functions should be tested.

steveb8n06:04:44

Thanks. I found the -instrument method which will work

👍 2