mrsteve
mrsteve

Reputation: 4142

check that a relation is symmetric in haskell

I want to use a haskell package for relations.

How can I check that a relation is symmetric? I.e., a function that given a relation returns true, if for all a b, a rel b implies b rel a.

Upvotes: 0

Views: 1045

Answers (2)

Tom Ellis
Tom Ellis

Reputation: 9414

import Data.Relation

swap :: (a, b) -> (b, a)
swap (a, b) = (b, a)

inverse :: (Ord a, Ord b) => Relation a b -> Relation b a
inverse = fromList . map swap . toList

symmetric :: Ord a => Relation a a -> Bool
symmetric r = r == inverse r

Upvotes: 0

bheklilr
bheklilr

Reputation: 54058

I haven't used the relations package before, but it looks like this works:

import Data.Relation

symmetric :: Ord a => Relation a a -> Bool
symmetric rel = and [member b a rel | (a, b) <- toList rel]

To test:

> symmetric $ fromList [(1, 2), (2, 1)]
True
> symmetric $ fromList [(1, 2), (2, 3)]
False

Upvotes: 1

Related Questions