Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: add element to a vector inside a map

I have this map

(def m {:a "aaa" :b {:c ["ss" "gg"]}})

I want to update it to this (add "uu" to the vector :c):

{:a "aaa" :b {:c ["ss" "gg" "uu"]}}

This is what I came up with and I hate it:

(assoc-in m [:b :c] (conj (get-in m [:b :c]) "uu"))

How should I be doing it?

like image 499
siltalau Avatar asked Feb 19 '16 07:02

siltalau


1 Answers

(update-in m [:b :c] conj "uu")

The way I think of it is that update-in gets you there and calls a function that receives not only the state that is there, but also the remaining parameters. So here conj will be called with ["ss" "gg"] and "uu", and the value of key :c in the data structure will become ["ss" "gg" "uu"].

assoc-in does not get any initial state, hence in your example you are having to labour to create what is there all over again.

like image 68
Chris Murphy Avatar answered Sep 28 '22 10:09

Chris Murphy