AppleJuice
AppleJuice

Reputation: 13

Checking cyclic list of tuples in Haskell

I'm fairly new to Haskell and I'm trying to write a function that checks to see if the domino pieces are in a perfect cycle. The dominos are tuples of two items, and all are in one list. The condition is that the snd of a tuple must be equal to the fst of the next one, and also the fst of the first tuple and snd of the last one should be equal. so for example:

[(2, 2)] -> true
[(5, 2), (2, 3), (3, 5)] -> true
[(5, 1), (2, 3), (3, 5)] -> false

Here's what I have so far (minimal reproducible version). I think the problem with it is that it doesn't check the first and last one with each other but I have no idea how I would go about solving it:

cycle [(x, y)] = x == y
cycle [(x, y), (a, b)] = and (y == a, x == b)
cycle (head:tail) = do
  let (headOfTail:restOfTail) = tail
  and (snd head == fst headOfTail, cycle (tail))

Thank you in advance!

Upvotes: 0

Views: 249

Answers (1)

DDub
DDub

Reputation: 3924

One way to solve a problem like this is to use the transitive property of dominoes to make a "virtual" domino. For instance, we can start with a pattern match like so:

cycle ((a,b):(c,d):rest) = ...

At this point, if we know that b and c are equal, then we can pretend we have one big domino that starts with a on one side and has d on the other side. If this new domino (a,d) works with the rest of our dominoes, then we should be good.

See if you can fill in the code!

Upvotes: 4

Related Questions