1

我正在使用clojure.core.match并看到以下错误:

不能让限定名

我的代码类似于:

(match [msg-type]
       [MsgType/TYPE_1] (do-type-1-thing)
       [MsgType/TYPE_2] (do-type-2-thing))

JavaMsgType/TYPE_1类的来源:

public class MsgType {
    public static final String TYPE_1 = "1";
    public static final String TYPE_2 = "2";
}

此错误是什么意思,我该如何解决?

4

2 回答 2

1

In general, pattern matching is not the right tool for comparing one variable with another. Patterns are supposed to be either literals such as 1 or :a, destructuring expressions or variables to be bound. So, for example, take this expression:

(let [a 1
      b 2]
  (match [2]
    [a] "It matched A"
    [b] "It matched B"))

You might expect it to yield "It matched B" since the variable b is equal to 2, but in fact it will bind the value 2 to a new variable named a and yield "It matched A".

I think you're looking for condp =. It's basically what you wish case would be.

(condp = msg-type
  MsgType/TYPE_1 (do-type-1-thing)
  MsgType/TYPE_2 (do-type-2-thing))
于 2014-02-26T18:42:12.160 回答
1

这个问题似乎与宏名称绑定有关,尽管我对宏很陌生,但我并不深入了解它。

最初我希望使用case而不是match证明可行的解决方法:

(case msg-type
      MsgType/TYPE_1 (do-type-1-thing)
      MsgType/TYPE_2 (do-type-2-thing))

但是,上述方法不起作用。case匹配符号MsgType/TYPE_n,而不是对该符号的评估。

到目前为止,我发现的最好的方法是将传入的值转换为关键字并以这种方式匹配:

(def type->keyword
     {MsgType/TYPE_1 :type-1
      MsgType/TYPE_2 :type-2})

(case (type->keyword msg-type)
      :type-1 (do-type-1-thing)
      :type-2 (do-type-2-thing))
于 2014-02-25T11:03:03.150 回答