Clojure has a very nice destructuring syntax, which works for both arrays and maps.
I am often confused between the two, meaning I'm not sure which one to choose. When should I use maps as parameters, and when should use an array ?
For instance, I came accross the following data, I want to pass a longitude and a latitude. I could pass it either as {:lat 12 :lng 34}
or [12 34]
, or as two parameters.
Note : I don't use two parameters since I think it's nicer to have a coords
binding.
Then suppose I want to add new fields (precision, altitude, timestamp...), it seems that the advantage then goes to the map :
- An array doesn't seem very readable with more parameters (you have to look at the prototype to understand the destructuring and therefore the parameters used).
- In a map I can add new fields and printing it is self-descriptive (keys acts as labels).
But then I often end up with functions taking a big options
parameter as a map, with some unrelated sub-options. It feels a bit bloated, even with just 10 keys.
So, when should I use map, and when should I use arrays in my function parameters ? What are the pro/cons in terms of readability/extensibility/performance ? Also, could core.match
help in that case ?
user=> (assoc (LngLat. 0 0) :lat 3) #user.LngLat{:lng 0, :lat 3}
anduser=> (map->LngLat {:lat 3 :lng 2}) #user.LngLat{:lng 2, :lat 3}
how would you do that without key-names ? – birdspider{:x :y}
map and a my.name.space.CartesianFoobar{:x :y}
map – birdspider