如何使用clojure.core.match匹配层次结构?
假设我有一个特殊的实体层次结构,表示为Clojure关键字,如下所示:如何使用clojure.core.match匹配层次结构?,clojure,pattern-matching,Clojure,Pattern Matching,假设我有一个特殊的实体层次结构,表示为Clojure关键字,如下所示: (def h (-> (make-hierarchy) (derive :animal :feline) (derive :feline :cat) (derive :feline :lion) (derive :feline :tiger))) 编写匹配层次结构函数以使这些人为示例返回预期结果的最佳方法(最好使用)是什么: (defn example [x
(def h
(-> (make-hierarchy)
(derive :animal :feline)
(derive :feline :cat)
(derive :feline :lion)
(derive :feline :tiger)))
编写匹配层次结构
函数以使这些人为示例返回预期结果的最佳方法(最好使用)是什么:
(defn example [x y]
(match-hierarchy h [x y]
[:cat :cat] 0
[:cat :feline] 1
[:cat :animal] 2
[:animal :animal] 3))
(example :cat :cat)
;=> 0
(example :cat :tiger)
;=> 1
(example :tiger :tiger)
;=> 3
i、 例如,match hierarchy
应该返回与第一个子句对应的值,该子句的元素要么等于所匹配值的对应元素,要么等于其(直接或间接)祖先
我很高兴使用自定义的东西而不是makehierarchy
来创建层次结构。如果有其他选项,我也很高兴不使用core.match。但是,我需要它来处理预先存在的类的对象,比如数字(例如,我想说3
是:正整数
是:整数
是:数字
)
背景:我正在用Clojure编写一个玩具x86汇编程序,我需要根据指令的名称和操作数来汇编指令。目前,我的代码包括以下内容:
(match [(-> instr name keyword) (operand-type op1) (operand-type op2)]
;; other options
[:int :imm nil] (if (= op1 3)
{:opcode 0xcc}
{:opcode 0xcd, :immediate (imm 8 op1)})
(也就是说,一条INT指令组合成两个字节,0xcd
,后跟中断号,除非它是int3
,在这种情况下,它只有一个字节,0xcc
)。然而,我觉得这有点难看,我正在寻找一种更优雅的方法。所以我想说一些关于
(asm-match [(-> instr name keyword) op1 op2]
;; other options
[:int 3 nil] {:opcode 0xcc}
[:int :imm nil] {:opcode 0xcd, :immediate (imm 8 op1)})
这对你不管用吗
这对你不管用吗
(match [(-> instr name keyword) op1 (operand-type op1) (operand-type op2)]
[:int 3 :imm nil] {:opcode 0xcc}
[:int _ :imm nil] {:opcode 0xcd, :immediate (imm 8 op1)})