Question

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.

Était-ce utile?

La solution

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

Autres conseils

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top