Thursday, April 9, 2009

Manipulating an inner item - (in-place editing)

If you have nested associative structure than using assoc-in and update-in you can manipulate the inner structured item and get back a newly nested structure.

update-in takes the sequence of keys to find the location and a function to apply to the old value at that location:

(def m {:a [1 2 3]})
(update-in m [:a] conj 4)
=> {:a [1 2 3 4]}

Nested map update
(def m {:a {:b [1 2 3]}})
(update-in m [:a :b] conj 4)
=> {:a {:b [1 2 3 4]}}

Apply merge function to an inner map
(def m {:a 1 :config {:b 1}})
(update-in m [:config] merge {:b 3})
=> {:a 1, :config {:b 3}}

We can also apply the same functions to the vectors also. Vectors are associative maps and index are the keys.

(def v [:a {:c 2, :b 1} :d])
(v 2)
=> :d ;Item at the 3rd index

We can use both sequential and associative de-structuring binds on vectors:
(let [{fred 2} v]
fred)
=> :d

assoc-in also takes the sequence of keys and a new value. The following code is locating the 2nd item in the vector. assoc-in is adding the [:rows 42] key value pair to the found map and update-in is applying assoc to the found map with the given key value pairs.

(assoc-in v [1 :rows] 42)
=> [:a {:rows 42, :c 2, :b 1} :d]

(update-in v [1] assoc :rows 42 :cols 21)
=> [:a {:cols 21, :rows 42, :c 2, :b 1} :d]

No comments:

Post a Comment