Clojure Programming/Examples/API Examples/Structure Tools
Appearance
accessor
[edit | edit source]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"
assoc
[edit | edit source]See struct-map for more.
defstruct
[edit | edit source]See struct-map for more.
struct
[edit | edit source]See struct-map for more.
struct-map
[edit | edit source]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}