Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the best way in clojure to swap! an atom if it's nil?

Tags:

clojure

Say I have a atom initially set to 0. I would like to initialize it only if it is not previously initialized,

What I have now:

(swap! atom #(if % % (initialize)))

However, this just doesn't look idiomatic to me.

There must be a more readable way right?

like image 298
LoveProgramming Avatar asked Jun 07 '16 17:06

LoveProgramming


1 Answers

Often you can use fnil to avoid needing to do the initialization check in the first place. For instance (swap! counts update word (fnil inc 0)) is saying increment the value at key word in counts, but if there is no value there use 0.

like image 145
Timothy Pratley Avatar answered Sep 20 '22 19:09

Timothy Pratley