metosin / malli

High-performance data-driven data specification library for Clojure/Script.
Eclipse Public License 2.0
1.44k stars 204 forks source link

mx/defn and malli.destructure/parse unexpected handling of seqexps #1005

Open larkery opened 5 months ago

larkery commented 5 months ago

If I write

(require '[malli.experimental :as mx])
(require '[malli.core :as m])

(mx/defn ^:malli/always f [xs :- [:* :int]]
  (malli.core/validate [:* :int] xs))

(f 1)
;; => false

(f [1])
;; => Execution error (ExceptionInfo) at malli.core/-exception (core.cljc:136).
;;    :malli.core/invalid-input

(m/validate [:* :int] [1])
;; => true

I would expect (f 1) to throw an except and (f [1]) to return true.

I think this is because the schemas for the arguments are combined using [:cat ...] and [:cat [:* :int]] 'flattens' the expression, so [[1]] is not valid for [:cat [:* :int]]. In this simple case the args schema should be something like [:tuple [:* :int]] for which [[1]] is valid.

Of course this is not so simple for varargs.

ikitommi commented 5 months ago

Yes, this is because of the auto-flattening of sequence schemas so it's a feature. You can escape it by wrapping it with non-sequence schema like :schema:

(mx/defn ^:malli/always f [xs :- [:schema [:* :int]]]
  (malli.core/validate [:* :int] xs))

or just use non-sequential like :vector:

(mx/defn ^:malli/always f [xs :- [:vector :int]]
  (malli.core/validate [:* :int] xs))

I don't think we should change this, maybe just document this into https://github.com/metosin/malli/blob/master/docs/function-schemas.md. PR most welcome on this.

ikitommi commented 5 months ago

would you have time to document this? e.g. PR most welcome

larkery commented 5 months ago

The auto flattening is good in general but maybe not what's wanted for parsing arg vectors? I can't think of a situation where I'd want it, but I might be lacking imagination :)

Would it be preferable to document it, or to insert the wrapping :schema automatically when using malli.destructure/parse?

Happy to have a go at either when I have a minute.

ikitommi commented 4 months ago

No auto-wrapping now, flattening is needed to describe Varargs. Thanks!