Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fn guard #1000

Merged
merged 6 commits into from
Jan 27, 2024
Merged

Fn guard #1000

merged 6 commits into from
Jan 27, 2024

Conversation

ikitommi
Copy link
Member

Function Guards

:=> accepts optional third child, a guard schema that is used to validate a vector of function arguments and return value.

;; function schema of arg:int -> ret:int, where arg < ret
;; with generative function checking always enabled
(def input<output
  (m/schema
   [:=>
    [:cat :int]
    :int
    [:fn {:error/message "argument should be less than return"}
     (fn [[[arg] ret]] (< arg ret))]]
   {::m/function-checker mg/function-checker}))

(m/explain input<output (fn [x] (inc x)))
; nil

(m/explain input<output (fn [x] x))
;{:schema ...
; :value #object[user$eval19073$fn__19074],
; :errors ({:path [],
;           :in [],
;           :schema ...,
;           :value #object[user$eval19073$fn__19074],
;           :check {:total-nodes-visited 1,
;                   :result false,
;                   :result-data nil,
;                   :smallest [(0)],
;                   :time-shrinking-ms 0,
;                   :pass? false,
;                   :depth 0,
;                   :malli.core/result 0}},
;          {:path [2],
;           :in [],
;           :schema [:fn
;                    #:error{:message "argument should be less than return"}
;                    (fn [[[arg] ret]] (< arg ret))],
;           :value [(0) 0]})}

(me/humanize *1)
; ["invalid function" "argument should be less than return"]

Identical schema using the Schema AST syntax:

(m/from-ast
 {:type :=>
  :input {:type :cat
          :children [{:type :int}]}
  :output {:type :int}
  :guard {:type :fn
          :value (fn [[[arg] ret]] (< arg ret))
          :properties {:error/message "argument should be less than return"}}}
 {::m/function-checker mg/function-checker})

@ikitommi ikitommi merged commit 5bdf403 into master Jan 27, 2024
9 checks passed
@allentiak
Copy link

Thank you so much for this, @ikitommi !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants