I want to generate pythagorean triples in Haskell using infinities lists. What's wrong with my code:
trojkaty = [(a,b,c) | a <- [1..], b <- [1..], c <- [1..], (a^2)+(b^2)==(c^2)]
Try expressing the upper bounds for a
and b
in terms of the intermediate value of c
, otherwise it will force all the entire list of infinite values before checking the last condition.
trojkaty :: [(Int, Int, Int)]
trojkaty = [(a,b,c) | c <- [2..], b <- [2..c-1], a <- [2..b-1], a^2 + b^2 == c^2]
main = do
print $ take 5 trojkaty
This will try infinitely many values of c
for a=1
and b=1
before it even tries b=2
.
One alternative possibility is to enforce that c >= a >= b
:
[(a,b,c) | c <- [1..], a <- [1..c], b <- [1..a], (a^2)+(b^2)==(c^2)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With