Last modified on 15 June 2009, at 03:13

Clojure Programming/Examples/API Examples/Structure Tools

accessorEdit

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"


assocEdit

See struct-map for more.

defstructEdit

See struct-map for more.

structEdit

See struct-map for more.

struct-mapEdit

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}