Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way to change a value on a map on clojure

Tags:

clojure

Alright, I'm new to clojure, this should be easy but for the life of me I can't find the answer

Let's say I have this map

(def mymap {:a 10 :b 15})

Now I want to change the value of :a to 5. I don't know how to do this properly

I know update and assoc can make changes but they both receive a function as last argument, which applies to the value. I don't want that, I don't want any function to run, I just want to simply set :a to 5.

I think I can pass an anonymous function that simply returns 5 and ignores the arg, but is this the right way? Doesn't look good to me

(update mymap :a (fn [arg] 5))

like image 653
GBarroso Avatar asked Jan 27 '23 15:01

GBarroso


1 Answers

assoc does not take a function as its last argument; unless you were wanting to associate a function with a key in the map. (assoc mymap :a 5) does what you want.

I'll add though, update, which does take a function, could be used here as well when combined with constantly or just another function (although there's no reason to use them over assoc):

; constantly returns a function that throws away any arguments given to it,
; and "constantly" returns the given value
(update mymap :a (constantly 5))

; Basically the same as above
(update mymap :a (fn [_] 5))
like image 160
Carcigenicate Avatar answered Feb 04 '23 00:02

Carcigenicate