检查haskell中的关系是否对称

时间:2014-05-07 04:22:49

标签: haskell relation

我想使用haskell package for relations

如何检查关系是否对称?即,给定关系的函数返回true,如果对于所有b,则rel b表示b rel a。

2 个答案:

答案 0 :(得分:2)

之前我没有使用过关系包,但看起来这样有效:

import Data.Relation

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

测试:

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

答案 1 :(得分:0)

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