6

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?

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

3

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 

Comments

2

You could try this:

import Control.Applicative mylookup :: (Ord a) => (a,a) -> Map (a,a) Int -> Maybe Int mylookup (x,y) m = lookup (x,y) m <|> lookup (y,x) m 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.