跳转到内容

Clojure 编程/示例/API 示例/结构工具

来自维基教科书,开放的书籍,开放的世界
user=> (defstruct employee :name :id)                    
#'user/employee

user=> (def e (struct employee "John" 123))
#'user/e

user=> e
{:name "John", :id 123}

user=> ("name" e) ; FAIL: string not an accessor
java.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0)

user=> (:name e)                             
"John"

user=> (def employee-name (accessor employee :name)) ; bind accessor to e-name
#'user/employee-name

user=> (employee-name e) ; use accessor
"John"

更多信息,请参见 struct-map

defstruct

[编辑 | 编辑源代码]

更多信息,请参见 struct-map

更多信息,请参见 struct-map

struct-map

[编辑 | 编辑源代码]
user=> (defstruct employee :name :id)
#'user/employee

user=> (struct employee "Mr. X" 10)
{:name "Mr. X", :id 10}

user=> (struct-map employee :id 20 :name "Mr. Y")
{:name "Mr. Y", :id 20}

user=> (def a (struct-map employee :id 20 :name "Mr. Y"))
#'user/a

user=> (def b (struct employee "Mr. X" 10))
#'user/b

user=> (:name a) ; observe that :name is an accessor
"Mr. Y"

user=> (:id b)  ; same with :id
10

user=> (b :id)
10

user=> (b :name)
"Mr. X"

user=> (assoc a :name "New Name")
{:name "New Name", :id 20}

user=> a          ; note that 'a' is immutable and did not change
{:name "Mr. Y", :id 20}

user=> (def a1 (assoc a :name "Another New Name")) ; bind to a1
#'user/a1

user=> a1
{:name "Another New Name", :id 20}
华夏公益教科书