I define a function, which takes two parameters – map and a key. The key is referenced from the map parameter decomposition
(defn myfunc [{v k} k]
v)
when I call:
(myfunc {:a 10} :a)
It surprisingly produces expected result: 10
Similar thing in the let:
(let [{v k} {:a 10} k :a] v)
fails, because k is not defined at the moment, when first part is evaluated.
My question is: why decomposition inside function parameters behaves differently compared to decomposition in let expressions?
Macroexpanding the
defnform I get the equivalent of this (removed .withMeta stuff and reformatted):So here we can see that the
{v k}map is in fact first assigned to a local variablep__11393. Then theifstatement tests if that variable is in fact a sequence and turns it into a hash-map if so, otherwise leaves it as it is. Importantly, the value assigned tokis looked up in the map after all of this happens, thus this works without error (and also would if:awasn’t in the map,getreturnsnilin that case).On the other hand macroexpanding the
letform I getand here we can see that
vgets the result of(get map__11431 k), butkisn’t defined at this point yet, hence the error.