malli

Shagun Agrawal 2024-11-15T13:56:15.424309Z

Hi ! I am not able to use a set as a predicate function while making the schema. I need to check whether the passed in value belongs inside a set.

(def MySchema [:fn [x] (contains? #{:a :b :c} x)])  
This works, but then I also need to supply the error message. Is there any idiomatic way of doing this ? Theres :enum , but in that I noticed I needed to list out all the options beforehand. [:enum :a :c :d] , but I want to use the set directly.

Stig Brautaset 2024-11-15T14:46:12.810679Z

Could you use unquote-splice?

(def s #{:a :b :c})
(def MySchema `[:enum ~@s])
(prn MySchema)
;; => [:enum :c :b :a]

(require '[malli.generator :as mg])
(mg/sample MySchema)
;; => (:b :b :a :a :c :c :a :b :a :c)

Shagun Agrawal 2024-11-15T15:01:06.323069Z

This worked ! Thanks. Wasn't familiar with this function. Only seen it code snippets in macros. It's evaluating the s, which gives it the set itself, and it's placing those values in it's place. So it becomes [:enum :a :b :c] .

Franco Gasperino 2024-11-16T01:45:54.751409Z

(apply into [:enum] #{:a :b :c}) or similar should also work (on mobile, cannot verify)

👍 1