Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure - destructuring array vs map

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 ?

like image 804
nha Avatar asked Oct 29 '25 09:10

nha


1 Answers

To summarize (although there's probably much more to it)

I'd say that position based data structures like vectors hit their limit very early. Especially if the data structure is used in more than a few places and is more "descriptive" than "listy".

Why maps?

Initially they are easy to work with and very flexible, further on in development they can easily be exchanged for records which are nearly as flexible as maps but:

  • are actuall classes/types
  • therefore have pure-java field access characterisics
  • therefore play well with protocols/interfaces
  • but are nearly as flexible as maps and
  • play nicely with various destructurings
  • they provide a suite of util functions you do not have to implement yourself
    • (map->LngLat {...}) (produces a LngLat from a map) and
    • (apply ->LngLat [...]) (constructs a LngLat from a vector)
    • probably more ...
like image 184
birdspider Avatar answered Oct 31 '25 12:10

birdspider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!