How does a key as a function of a map and vice versa work the same in Clojure?

({:x 10, :y 20, :z 50} :y) gives 20 

as well as

 (:y {:x 10, :y 20, :z 50}) gives 20 

How does it work inside both cases,

For cards as a function, I can understand that you can distinguish between forms, realizing that the first value is a map.

but how does a key become a function? at run time, the key can be any type of value, so how does the runtime understand that it should consider this value as a function?

+4
source share
1 answer

Maps are functions from docs :

Cards implement IFn, for invoke () one argument (key) with an optional second argument (default value), that is, cards are functions of their keys. nil keys and values ​​are ok.

So this is:

 ({:x 10, :y 20, :z 50} :y) 

applies the function {:x 10, :y 20, :z 50} to :y .

Keywords are also functions, quoting docs :

Keywords implement IFn for invoke () of one argument (map) with an optional second argument (default value). For example (: mykey my-hash-map: none) means the same as (get my-hash-map: mykey: none)

So when you do:

 (:y {:x 10, :y 20, :z 50}) 

you actually call :y with {:x 10, :y 20, :z 50} as an argument.

In principle, everything that implements IFn and is in the way of classes can be considered as a function.

+4
source

Source: https://habr.com/ru/post/1501440/


All Articles