I have written the following function that returns an infinite list of 3-tuple members, (a, b, c) according to the definition of a Pythagorean triples: a^2 + b^2 = c^2. I need to be able to check if a given tuple (a, b, c) is a valid Pythagorean triple. The way I do this is by generating an infinite list of tuples by means of the function and I pass this list to elem
along with the 3-tuple I want to check.
However, this does not terminate when it matches my 3-tuple to a member of the infinite list.
Code:
pythagoreanTriples::[(Integer, Integer, Integer)]
pythagoreanTriples = [(a, b, c) | a <- [2..], b <- [a+1..],
c <- [b+1..], a*a + b*b == c*c ]
main = do
print $ elem (30, 72, 78) (pythagoreanTriples)
I know the logic is correct, because I have tried modifying the above function to produce an finite list and the logic works very nicely:
pythagoreanTriples n = [(a, b, c) | a <- [2..n], b <- [a+1..n],
c <- [b+1..n], a*a + b*b == c*c ]
main = do
print $ elem (30, 72, 78) (pythagoreanTriples 100)
However, it must be done with an infinite list. Please suggest to me how I can make it work. Thanks.
Start with your finite code,
and simply make it work for any
n
from 1 and up:(but this produces a lot of duplicates). I'd prefer to first fix the biggest,
c
value, and then find thea
andb
such thata < b < c
, and the condition holds:but what do we need that
n
for, now? We don't:So that
(the case
a==b
is impossible, becausesqrt(2)
is an irrational number).