Fork me on GitHub
#hyperfiddle
<
2023-03-13
>
Can08:03:25

hello, can I ask something? The calculation codes are working as I wanted. But I want to change that code more simply and readable. So I defined a function to call calculations. But when I call the function but that doesn't work. Why? Can anyone help me?

2
Geoffrey Gaillard08:03:34

Prefix VS Infix notation. In, say, python you’d write s * w / h * h – *in*fix In Clojure: (/ (* s w) (* h h)) – *pre*fix See, in Python / and * are operators. And they have the famous operator precedence rules (PEMDAS). s * w / h * h works because multiplication has precedence over division. This is hard to remember and get right. Lisps (like Clojure) are simpler: • / and * are just functions • The first elements in a list ( … ) is considered a function to be called. -> no need for operator precedence.

Can09:03:30

Ops that's a very basic mistake, thank you so much. Still my brain works like java python-dev 🙂

🙂 2
Dustin Getz13:03:26

Please call (e/watch ...) only once per atom and share the return value. Otherwise, each individual watch will trigger separately, causing extra wasteful computation and also causing your app to see inconsistent states ("reaction glitch")

Dustin Getz13:03:38

The same applies to swap!, it is better to modify the atom "as a transaction", like this:

(def !state (atom {}))

; bad - each swap! will cause your app to update
(swap! !state assoc :a 1)
(swap! !state assoc :b 2)
(swap! !state assoc :c 3)

; good - one transaction = one update
(swap! !state assoc :a 1 :b 2 :c 3)
(swap! !state #(merge % {:a 1 :b 2 :c 3}))
(swap! !state merge {:a 1 :b 2 :c 3})
(swap! !state #(-> %
                 (assoc :a 1) ; composable updates
                 (assoc :b 2)
                 (assoc :c 3)))