Is this clojure.core.match error or is it just me?

(match
   [[1 2 3]]
   [(:or [_ _ 2] 
         [3 _ _])] :a0

   [(:or [_ _ 1] 
         [1 _ _])] :a1
   :else :else)

=> :else

In this first snippet, I expected it to return :a1.

Weird

It works:

(match
   [[1 2 3]]
   [(:or [_ _ 2] 
         [1 _ _])] :a0

   [(:or [_ _ 1] 
         [3 _ _])] :a1
   :else :else)

=> :a0

Is this the expected behavior?

+4
source share
3 answers

I believe this is a mistake specialize-or-pattern-row. I believe that the test is groupable?incorrect, because in your case it succeeds for your two OrPatterns, and therefore the second OrPatternis replaced by the extension of the first ( ps- these are the subpatterns of the first OrPattern).

You can get around this by adding a dummy template to your second one :or, which will force it groupable?to return false:

(match
   [[1 2 3]]
   [(:or [_ _ 2] 
         [1 _ _])] :a0

   [(:or [_ _ 1] 
         [3 _ _]
         :dummy)] :a1
   :else :else)

, specialize-or-pattern-row (copy-as :as OrPattern, :as ):

(defn copy-as [dest src]
  (if-let [as (-> src meta :as)]
    (vary-meta dest assoc :as as)
    dest))

(defn specialize-or-pattern-row [row pat ps]
  (let [p (first row)]
    (if (identical? p pat)
      (map (fn [p] (update-pattern row 0 (copy-as p pat))) ps)
      [row])))
+2

, , :or . , :

[4 (:or 5 6 7) _] :a1

,

(match
         [[1 2 3]]
         [[_ _ 2]] :a0
         [[3 _ _]] :a0

         [[_ _ 1]] :a1
         [[1 _ _]] :a1
         :else :else)

, , . , .

+3

reddit:

core.match. , .

(match
 [[1]]
 [(:or [3] [])] :a0
 [(:or [1] [])] :a1
 :else :else)

: else. . .

(let
 [x [1]]
  (cond (and (vector? x) (== (count x) 1) (= (nth x 0)  3)) :a0
        (and (vector? x) (== (count x) 0)) :a0
        (and (vector? x) (== (count x) 1) (= (nth x 0) 3)) :a1
        (and (vector? x) (== (count x) 0)) :a1))

On the 5th line you can see an error, it is 3 instead of 1. For some reason, it takes the value that is in the first: or a template instead of the second value of the line.

This patch seems to fix the problem.

Thanks everyone!

PS: I have not tested the patch yet.

0
source

Source: https://habr.com/ru/post/1676357/


All Articles