Fork me on GitHub
#clojure
<
2023-11-08
>
pez11:11:48

What’s the reason update isn’t nil safe?

delaguardo11:11:49

what do you mean?

(update nil :foo assoc :x 42)
;; => {:foo {:x 42}}

lispyclouds11:11:21

@U0ETXRFEW maybe it depends on the function that youre passing?

oyakushev11:11:36

You probably mean that the function that you use is not nil-safe

oyakushev11:11:51

(update {} :foo (fnil inc 0))

👆 1
delaguardo11:11:07

from the docstring:

If the key does not exist, nil is passed as the old value.

lispyclouds11:11:54

update is made of assoc and get calls so should be nil safe

pez12:11:24

> You probably mean that the function that you use is not nil-safe Ah, yes, I’m stooopid! And it was inc, even. 😃

pez12:11:13

Thanks, guys. I’m preparing a course and this one puzzled me. Now I’m much better prepared! 🙏

👍 1
pez12:11:49

I should have checked the stack trace this time… > ; Execution error (NullPointerException) at get-started.my-basics/eval7831 (REPL:34). > ; Cannot invoke “Object.getClass()” because “x” is null

pez12:11:54

(update nil :a assoc :b 1) ;=> {:a {:b 1}}
(update nil nil assoc :b 1) ;=> {nil {:b 1}}
😃

Ian Fernandez17:11:17

I've really like the assoc-if / assoc-some and their friends, feels very useful

🙏 1
reefersleep10:11:09

we use medley.core/assoc-some extensively

metal 2
grav16:11:23

Call me a purist:

(cond-> my-map
  v1 (assoc :k1 v1)
  v2 (assoc :k2 v2))

1
oyakushev16:11:42

@U052XLL3A Doesn't work if v1 is an expression.

👍 1
grav16:11:02

@U06PNK4HG Not sure I follow - you mean it's evaluated twice? It would still work, though?

oyakushev16:11:21

Yes, I mean that it would have to be evaluated twice.

👍 1
reefersleep07:11:35

I use cond-> and its sister extensively as well! Great fns