Welcome! Please see the About page for a little more info on how this works.

0 votes
in Clojure by

Hi!
What is idiomatic way to represent an immutable pair in Clojure where pair is an immutable container for two component (kinda first and last) which can't be modified after construction.

Use case is following -- create data structure with first and second components which will not be modified by consumers. Consumers will read first and second components using destructuring or first/second selectors.

I can see a de-facto way to represent it via vector.
There are other alternatives like:
- use list
- use MapEntry

it seems that list is "ligther" data structure than vector. Maybe using list to model pair for the use above has advantages? (less pressure on memory, etc.)

Thanks!

by
I'd start with a vector, for sure. `first` and `last` will work, as you mention, and in many contexts destructuring will result in elegant code. If performance became a problem (in 90%+ of cases it never will) you can do something platform specific to improve performance (a two-element java array, or js NativeArray, or similar)
by
"If performance became a problem (in 90%+ of cases it never will) you can do something platform specific to improve performance (a two-element java array, or js NativeArray, or similar)"

it's interesting does using list makes sense as the option before jumping into java stuff you enumerated?
it's really interesting what are the use cases where list should be used instead of the vector. Maybe pair case above is one of those cases.
by
Not really, no. You can look into the implementations of Clojure's list & vector if you're curious. The main use of lists in Clojure is to represent code (programs are written as mostly lists), in general, for data (like the case in your question), vectors are preferred.

1 Answer

+1 vote
by
selected by
 
Best answer

MapEntry is probably the closest match (and supports key and val).

...