malli

Casey 2025-03-17T07:29:17.052489Z

I'm trying to use malli's parse as a sort of pattern matching tool..

(m/parse [:altn
            [1 :keyword]
            [2 :string]]
           [:test])
  ;; => [1 test]

  (m/parse [:altn
            [1 :keyword]
            [2 :string]]
           ["wow"])
  ;; => [2 "wow"]
But when the first item in the pattern vectors are the same, it results in a duplicate-key error from malli:
(m/parse [:altn
            [1 :keyword]
            [1 :string]]
           ["fail"])

  ;; =>
  ;; clojure.lang.ExceptionInfo  :malli.core/duplicate-keys
  ;; {:type    :malli.core/duplicate-keys,
  ;;  :message :malli.core/duplicate-keys,
  ;;  :data    {:arr [1, {:order 0}, 1, {:order 1}]}}
Why is this? To be honest I don't understand why the working examples work, since the scalar 1 and 2 values are not valid malli schema parts, yet the entire :altn expression is a valid schema (as long as the first items aren't equal). I sort of lucked into finding out about this pattern matching feature (emergent feature?).

2025-03-17T19:11:24.723129Z

:altn :map :multi and others all share the same syntax [K [name schema] [name schema] ...]. The first part of the tuple is the name (the n in :altn).

2025-03-17T19:12:20.793869Z

It can be any value like in :map but duplicates are not allowed.

2025-03-17T19:12:59.038229Z

Because it's used to then recover which schema was used to parse the value via unparse.

Casey 2025-03-21T16:52:01.840279Z

Aha, ok that clears it up. So I can wrap my patterns in another layer of vectors and it works well.

Casey 2025-03-21T16:52:56.652069Z

btw, i'm using (abusing?) m/parse to do pattern matching on exceptions for error handlers, like pedestal does, but data driven instead of macros. it works very well now.

2025-03-21T17:39:11.220899Z

not familiar with the data format, but can you explain why you're unsure if it's the right tool?