struct - Clojure 结构嵌套在另一个结构中

标签 struct clojure nested

Clojure 中的结构中是否可以嵌套结构?考虑以下代码:

(defstruct rect :height :width)
(defstruct color-rect :color (struct rect))

(defn 
#^{:doc "Echoes the details of the rect passed to it"}
echo-rect
[r]
  (println (:color r))
  (println (:height r))
  (println (:width r)))

(def first-rect (struct rect 1 2))
;(def c-rect1 (struct color-rect 249 first-rect)) ;form 1
;output "249 nil nil"
(def c-rect1 (struct color-rect 249 1 2)) ;form 2
;output "Too many arguments to struct constructor

(echo-rect c-rect1)

当然,这是一个人为的示例,但在某些情况下,我想将大型数据结构分解为较小的子结构以使代码更易于维护。正如注释所示,如果我执行表格 1,我会得到“249 nil nil”,但如果我执行表格 2,我会得到“结构构造函数的参数太多”。

如果我以错误的方式处理这个问题,请告诉我应该做什么。搜索 Clojure google 群组并没有找到任何结果。

<小时/>

编辑:

我想我的问题陈述并不像我想象的那么清楚:

1.) 在 Clojure 中是否可以将一个结构嵌套在另一个结构中? (从下面来看,这是肯定的。)

2.) 如果是这样,正确的语法是什么? (同样,从下面来看,似乎有几种方法可以做到这一点。)

3.) 当一个结构体嵌套在另一个结构体中时,如何通过指定的键获取值?

我想我的示例代码并没有真正展示我想要做得很好。我将其添加到此处,以便搜索此问题的其他人可以更轻松地找到此问题及其答案。

最佳答案

我同意其他发帖者的观点,即结构映射并不真正支持继承。但是,如果您只想创建一个使用另一个结构体的键的新结构体,那么这将起作用:

; Create the rect struct
(defstruct rect :height :width)

; Create the color-rect using all the keys from rect, with color added on
(def color-rect (apply create-struct (cons :color (keys (struct rect)))))

(defn create-color-rect 
  "A constructor function that takes a color and a rect, or a color height and width"
  ([c r] (apply struct (concat [color-rect c] (vals r))))
  ([c h w] (struct color-rect c h w)))

您不需要 echo-r​​ect 函数,您可以简单地评估 struct map 实例以查看其中的内容:

user=> (def first-rect (struct rect 1 2))
#'user/first-rect
user=> first-rect
{:height 1, :width 2}
user=> (create-color-rect 249 first-rect)
{:color 249, :height 1, :width 2}
user=> (create-color-rect 249 1 2)
{:color 249, :height 1, :width 2}

关于struct - Clojure 结构嵌套在另一个结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/555013/

相关文章:

c - 在C编程中,有没有办法在子结构体(结构体中的结构体)中获取函数的返回值?

clojure - 在clojure中懒惰地构建集合

java - 用于穿越 NAT 的 clojure 友好 Java 库

clojure - 惰性序列——外部或内部的缺点

ecmascript-6 - 解构时可空嵌套对象上的 ES6 默认参数

go - 在括号中初始化 Go 结构有什么作用?

go - 在结构体中初始化结构体

powershell - 在Powershell中将嵌套的哈希表导出到CSV

javascript - AngularJS 将 ui-view 嵌套到 ng-repeat 中

ios - swift 结构体作为函数参数