Friday, April 29, 2016

How to add key value pair in hash map in Clojure . Hashmap Mutation

This is a Mutable hash map example . It shows the function add-keyvalue-to-map  works.
(ns clojure.examples.hello
 (:gen-class))
 
(def collection (atom {:ver "0.0.1" })) 
 
(defn add-keyvalue-to-map
"add a new key to map or if exist increment value corresponding for this key"
[param  collection]
    (def col-key (read-string (str ":" param)))
    ;( println "debug add-keyvalue-to-map.1")
 ;( println  col-key )
 ;( println  collection )
    (if-not (nil? (get @collection col-key ))
    ( swap! collection update-in [col-key] inc)
  ;; notice that the value swapped in, is part of the returned value
    ( swap! collection assoc col-key 1)
 ) ; if
)

(add-keyvalue-to-map "key1" collection)
(println collection)
(swap! collection update-in [:key1] inc)
(println collection)
(add-keyvalue-to-map "key3" collection)
(def my-key ( read-string ( str ":" "key4")))

(add-keyvalue-to-map "key4" collection)
(println collection)

(println (get @collection my-key ))
(println collection)
(swap! collection update-in [my-key] inc)
(add-keyvalue-to-map "key3" collection) (add-keyvalue-to-map "key3" collection) (add-keyvalue-to-map "key3" collection)
(println collection)

No comments: