Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map with unordered tuple as key

I have a mapping between a tuple with both parts of the same type and a Int.

Map (a,a) Int

Independent of the ordering of the as in the tuple I want later to be able to get it out of the map.

lookup (2,1) map == lookup (1,2) map

Is this possible without inserting the tuple twice?

like image 456
F. Böller Avatar asked Aug 13 '14 10:08

F. Böller


2 Answers

You can make the key (max a b, min a b).

like image 174
Ørjan Johansen Avatar answered Sep 28 '22 10:09

Ørjan Johansen


You can just sort the tuple and then use this to inseet the tuples (and search too):

sortTup :: (Ord a) => (a, a) -> (a, a)
sortTup (a, b) = (min a b, max a b)

Using it you would look something like this:

Prelude Data.Map> let a = Map.fromList [(sortTup (2,1), 5]
Prelude Data.Map> lookup (sortTup (1,2))
5
like image 29
ThreeFx Avatar answered Sep 28 '22 08:09

ThreeFx