{(a,c) | exists b, (a,b) in r1 and (b,c) in r2}.
relation :: [(Integer, Integer)] -> [(Integer, Integer)] -> [(Integer, Integer)]
relation r1 r2 = ?
I'm new to Haskell. I want to make this function shown above. I'm confused how to iterate each element in the list and how to access first element and second element of tuple.
CodePudding user response:
So let's start with the tuples. You can access the elements by pattern matching (x, y)
or use the fst
and snd
functions, e.g., fst myTuple == x
.
Then you want to match every tuple in r1 with every tuple in r2 and see if you can combine them. There are different ways to do it, but list comprehensions seem like the most elegant one:
[(x, z) | (x, y1) <- r1, (y2, z) <- r2, y1 == y2]
What does this mean? The first part of the comprehension is the result, i.e., we want a list of some (x, z)
. Then we destructure the two lists with the expressions containing the left arrow <-
. We named the tuple elements of each list element and the last part is the filter of the list comprehension. We only want to include values where y1 == y2
.