Re: compare-and-set deep value in hashmap atom

2016-02-01 Thread Matching Socks
There is another idiom to consider if you need to involve a side effect like notification. See http://clojure.org/reference/agents. You use a ref instead of an atom, you modify the ref and trigger the notification (by sending a function to an agent) inside a transaction, and the agent runs

compare-and-set deep value in hashmap atom

2016-02-01 Thread Jeremy Vuillermet
Hello, I'm making a game where players can choose a box in a grid to discover what's behind it. My data structure is an atom with {:grid-size 5, :picks {5 "player1}} where 5 is the box position in the grid. How can I be sure that two players can't pick the same box. From my understanding,

Re: compare-and-set deep value in hashmap atom

2016-02-01 Thread William la Forge
The easy way is the big atom approach. Put the entire structure in an atom and use swap! to make updates. First, the function passed to swap! should be free of side-effects, as swap! may need to call it more than once in the case of a collision. Second, within the function passed to swap! is

Re: compare-and-set deep value in hashmap atom

2016-02-01 Thread Jeremy Vuillermet
That's very clear thank you. Some follow up questions: In my case, I still need to notify every player that the resource is not available anymore and that is a side effect. Should I just make it idempotent so it doesn't matter if it's called more than once. If I check for the resource within the

Re: compare-and-set deep value in hashmap atom

2016-02-01 Thread William la Forge
True, but very bad practice. Better to check after the swap! completes to see if it was successful and then send the notifications. If you do the notifications within the swap! function, you are holding the atom for longer than need be and increasing the chance of contention. Contention means