简体   繁体   中英

How to create an empty collection in Clojure?

I am experimenting with using Clojure for modelling a certain set of data which are

  • 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).

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.

Same with

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

How can I bind my-complex-object to an empty collection?

You get error, because this expression (my-complex-object) calls function named my-complex-object. 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). If you do both in REPL, it will look like this:

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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