Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythagorean triples in Haskell using infinities lists

Tags:

haskell

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)]
like image 620
Chris Avatar asked Jan 19 '14 18:01

Chris


2 Answers

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
like image 50
Stephen Diehl Avatar answered Oct 10 '22 02:10

Stephen Diehl


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)]
like image 33
Louis Wasserman Avatar answered Oct 10 '22 03:10

Louis Wasserman