Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

Symmetric Relation in Haskell

I'm working with relations and I want to find whether a relation is symmetric.

To find that a relation is symmetric, we need to find two tuples such that: [(a,b), (b,a)].

This is what I've got so far:

simmetry:: Eq a => [(a,a)] -> [a]
simmetry [] = []
simmetry (x:xs)
            | (fst x `elem` map snd xs) && (snd x `elem` map fst xs) = fst x : (simmetry xs)
            | otherwise = simmetry xs

What this function does is, it grabs a tuple x and checks that it finds its first element in another tuple as the second position, as well as checking that the second element is in another tuple as the first position.

However I'm missing out on the part where I have to check that the other tuple is the same one for both conditions. With my code, something like this: [(a,b),(b,c),(d,a)] would work.

P.D: simmetry returns [a] for testing purposes.

I'm out of ideas, any tips are highly appreciated!

question from:https://stackoverflow.com/questions/65953083/symmetric-relation-in-haskell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you want to check is: for every tuple (x,y) in the list, (y,x) should also be present. You can express that quite directly in Haskell:

isSymmetric :: Eq a => [(a,a)] -> Bool
isSymmetric l = all ((x,y) -> (y,x)`elem`l) l

This is actually doing some redundant work because it always also goes over (x,y) itself, which your not really interested in, but it doesn't really matter. However it's a good exercise to design this in a way so it doesn't go over the element itself; for this it's helpful to use an auxiliary function

foci :: [a] -> [(a,[a])]

witht the behaviour

foci [p,q,r] ≡ [(p,[q,r]), (q,[p,r]), (r,[p,q])]

Then you left with an all over the foci of the input list, i.e.

isSymmetric = all _ . foci

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...