Clojure Programming/Examples/API Examples/Structure Tools

From Wikibooks, open books for an open world
Jump to: navigation, search


user=> (defstruct employee :name :id)                                        

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

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)                                                         

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

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


See struct-map for more.


See struct-map for more.


See struct-map for more.


user=> (defstruct employee :name :id)

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=> (def b (struct employee "Mr. X" 10))

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

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

user=> (b :id)

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
{:name "Another New Name", :id 20}