Re:Try Clojure
by tmtvl on Wednesday May 22, 2024 @05:45PM
(#40447028)
So here's something which I, as a Lisper, don't understand: Clojure has syntax for hash tables (the curly braces), why doesn't it use those for let-bindings, instead choosing to use vector syntax? (Of course I prefer standard Lisp syntax which can easily be extended for multiple-value and destructuring bindings:
[ Parent
| on HN ]
Re:Try Clojure
by puredanger on Wednesday May 22, 2024 @05:48PM
(#40447077)
Maps are unordered, but let bindings are sequential so order matters.
And also, a variable can be rebound in later bindings!
I see, so Clojure's let works like Lisp's let*. I didn't know that, thanks for the explanation!
Clojure has some very expressive destructuring syntax as well:
https://clojure.org/guides/destructuring
What's so different to Clojure's ?
(let [a 1
[b c] (list 2 3)
[d e] [4 5]]
`(~a ~b ~c ~d ~e))
;; => (1 2 3 4 5)But what would be the equivalent of:
(let ((quotient remainder (floor x y)))
(+ (* quotient z)
(* remainder (floor z y))))
Where floor is a function which returns multiple values rather than a list or vector of results?Also, but this is entirely on me being an absolute dullard, I like having the brackets around each binding as a kind of guardrails for my mind to not lose track of where I am and what belongs where.
It's just:
(let [[quotient remainder] (floor x y)]
(+ (* quotient z)
(* remainder (first (floor z y)))))
Because in Clojure there's no multiple value bind, when you want to return many results from a function, you wrap it in a vector, and that means you than just destructure that vector. That also means, it's not smart enough to know if it's used in a single value context or multi value context, so you need to always get the value out of the vector, which is why I call first in that second call to floor.