gpt4 book ai didi

clojure - 使用可选键进行 defrecord

转载 作者:行者123 更新时间:2023-12-03 00:35:17 26 4
gpt4 key购买 nike

我是 clojure 的新手,基本上正在尝试遵循一些教程。我有一个关于 defrecord 的问题。

这是我正在尝试做的事情:

(defrecord somemap [key1 key2 key3 key4])

(defn give-me-map [m1 m2]
(somemap. m1 m2))

在上面的代码中,我希望将 key3key4 作为可选,这样我就不需要每次创建 时都给它们赋值>somemap 对象。

有类似的问题here ,但它与我在这里尝试做的相反。

那么是否可以使用可选字段定义 defrecord

最佳答案

当您使用(defrecord T [...])时,会创建两个工厂函数:->Tmap->T >.

第一个使用位置参数作为键。第二个将任意映射应用于记录。

您可以将 key3key4 保留在构造函数中并使用 map->somemap

(defrecord somemap [key1 key2 key3 key4])

(defn give-me-map
[key1 key2]
(map->somemap {:key1 key1 :key2 key2}))

关于clojure - 使用可选键进行 defrecord,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13391994/

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