gpt4 book ai didi

clojure - Om 下一个教程 : Correctly calling the get-people function

转载 作者:行者123 更新时间:2023-12-05 00:58:04 25 4
gpt4 key购买 nike

我目前正在关注 om-next tutorial .在 Adding Reads部分,有一个功能 get-people被定义为。与此功能一起,init-data定义了包含人员列表的 map 。

(defn get-people [state key]
(let [st @state]
(into [] (map #(get-in st %)) (get st key))))

(def init-data {:list/one
[{:name "John", :points 0}
{:name "Mary", :points 0}
{:name "Bob", :points 0}],
:list/two
[{:name "Mary", :points 0, :age 27}
{:name "Gwen", :points 0}
{:name "Jeff", :points 0}]})

这是我调用此函数的尝试。
(get-people (atom init-data) :list/one) ;; => [nil nil nil]

正如你所看到的,我只是得到一个向量 nil 。我不太明白我应该如何调用这个函数。有人可以帮我吗?谢谢!

最佳答案

好吧,我想通了。
init-data不是调用 get-people 的正确数据结构和。初始数据必须首先使用 Om 的 reconciler“核对”。 .您可以在本教程的 Normalization 中找到有关协调器的更多信息。部分。

调和init-data map 然后deref处理数据返回这个规范化的数据结构:

{:list/one
[[:person/by-name "John"]
[:person/by-name "Mary"]
[:person/by-name "Bob"]],
:list/two
[[:person/by-name "Mary"]
[:person/by-name "Gwen"]
[:person/by-name "Jeff"]],
:person/by-name
{"John" {:name "John", :points 0},
"Mary" {:name "Mary", :points 0, :age 27},
"Bob" {:name "Bob", :points 0},
"Gwen" {:name "Gwen", :points 0},
"Jeff" {:name "Jeff", :points 0}}}

这是对 get-people 的有效调用使用协调的 init-data 的函数:
; reconciled initial data
(def reconciled-data
{:list/one
[[:person/by-name "John"]
[:person/by-name "Mary"]
[:person/by-name "Bob"]],
:list/two
[[:person/by-name "Mary"]
[:person/by-name "Gwen"]
[:person/by-name "Jeff"]],
:person/by-name
{"John" {:name "John", :points 0},
"Mary" {:name "Mary", :points 0, :age 27},
"Bob" {:name "Bob", :points 0},
"Gwen" {:name "Gwen", :points 0},
"Jeff" {:name "Jeff", :points 0}}}

; correct function call
(get-people (atom reconciled-data) :list/one)

; returned results
[{:name "John", :points 0}
{:name "Mary", :points 0, :age 27}
{:name "Bob", :points 0}]

这是发生了什么:
  • 首先,该函数检索与 :list/one 关联的值。 key 。在这种情况下,该值是映射到 map 中的路径向量(每条路径本身就是一个向量)。
  • 接下来,映射路径并在每个向量上调用匿名函数。其中一个调用看起来像 (get-in st [:person/by-name "John"])并返回 {:name "John", :points 0} .
  • 将结果作为向量返回

  • 如果有人正在阅读本文并想进一步澄清,请告诉我。

    关于clojure - Om 下一个教程 : Correctly calling the get-people function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33491017/

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