简体   繁体   English

如何在 Clojure 中创建一个空集合?

[英]How to create an empty collection in Clojure?

I am experimenting with using Clojure for modelling a certain set of data which are我正在尝试使用 Clojure 对一组特定数据进行建模

  • not well defined (I am figuring out the optimal structures for those data while working with them) and定义不明确(我正在为这些数据找出最佳结构,同时使用它们)和
  • gradually being refined (when I first declare a certain object I know very little about it, as I am working on this project, I get to know more and more about it and want to capture it in Clojure).逐渐被完善(当我第一次声明某个 object 时,我对它知之甚少,因为我正在做这个项目,我越来越了解它并想在 Clojure 中捕获它)。

At the very start, I want that complex piece of data be just an empty collection.一开始,我希望那段复杂的数据只是一个空集合。 At this point I don't care whether it's a list, a set, or a vector.在这一点上,我不在乎它是列表、集合还是向量。

(ns clojure-playground.core
  (:gen-class))

(def my-complex-object (hash-set))

When I compile this file and enter (my-complex-object) in REPL, I get an error.当我编译这个文件并在 REPL 中输入(my-complex-object)时,我得到一个错误。

Same with

  • (def my-complex-object ()) , (def my-complex-object ()) ,
  • (def my-complex-object []) , (def my-complex-object []) ,
  • (def my-complex-object (list)) , and (def my-complex-object (list))
  • (def my-complex-object '(list)) . (def my-complex-object '(list))

How can I bind my-complex-object to an empty collection?如何将my-complex-object绑定到空集合?

You get error, because this expression (my-complex-object) calls function named my-complex-object.您会收到错误,因为此表达式(my-complex-object)调用名为 my-complex-object 的function Use any from these definitions:使用这些定义中的任何一个:

(def my-complex-object #{})
(def my-complex-object (hash-set))
(def my-complex-object ())
(def my-complex-object (list))
(def my-complex-object [])
(def my-complex-object (vector))

and then just evaluate my-complex-object (without parentheses).然后只评估my-complex-object (不带括号)。 If you do both in REPL, it will look like this:如果您在 REPL 中同时执行这两项操作,它将如下所示:

(def my-complex-object [])
=> #'clojure-playground.core/my-complex-object
my-complex-object
=> []

Note that each collection type has different behaviour for operations like conj , pop or handling duplicates.请注意,每种集合类型对于conjpop或处理重复项等操作都有不同的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM