gpt4 book ai didi

clojure - 这个 core.match 绑定(bind)示例如何工作?

转载 作者:行者123 更新时间:2023-12-04 01:27:11 25 4
gpt4 key购买 nike

查看此 example :

(let [x 1 y 2]
(match [x y]
[1 b] b
[a 2] a
:else nil))
;=> 2

我无法理解一些事情:

  1. 1 是否匹配 x 并绑定(bind)到 b
  2. 2 是否匹配 y 并绑定(bind)到 a
  3. 假设我得到了上面的两点,为什么要返回 a 而不是 b 考虑到它们都匹配 [x y] 的一部分。是因为它是最后一个子句吗?

最佳答案

将每个模式视为要与输入 [x y][1 2] 匹配的模板。

第一个模式是 [1 b] 匹配输入,因为第一个模板项是一个匹配的文字值 1,第二个模板项是一个 binding 将在输入的那个位置保存 any 值,在本例中恰好是 2b 绑定(bind)可以从 match 子句的右侧访问,就好像它是 let 绑定(bind)一样。

这个例子可能会更清楚地展示它:

(let [x 1 y 2]
(match [x y]
[1 b] [1 (inc b)] ;; recreate the input with (inc b)
[a 2] a ;; this never matches because prior match works
:else nil))
=> [1 3]

Does 2 match y and gets bound to a?

模式是一个匹配项,但这无关紧要,因为前面的模式已经是一个匹配项。如果匹配成功,a 将绑定(bind)到 1

关于clojure - 这个 core.match 绑定(bind)示例如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61695034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com