/* List comprehensions (Rosetta code) in Picat. http://rosettacode.org/wiki/List_comprehensions """ A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are that: - They should be distinct from (nested) for loops within the syntax of the language. - They should return either a list or an iterator (something that returns successive members of a collection, in order). - The syntax has parts corresponding to that of set-builder notation. Write a list comprehension that builds the list of all Pythagorean triples with elements between 1 and n. If the language has multiple ways for expressing such a construct (for example, direct list comprehensions and generators), write one example for each. """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ % import util. % import cp. main => go. go => N = 20, println(pyth1=pyth1(N)), println(pyth1b=pyth1b(N)), println(pyth2=pyth2(N)), println(pyth3=pyth3(N)), nl. pyth1(N) = [[A,B,C] : A in 1..N, B in A..N, C in B..N, A**2 + B**2 == C**2]. pyth1b(N) = {[A,B,C] : A in 1..N, B in A..N, C in B..N, A**2 + B**2 == C**2}. % Using between and findall pyth2(N) = findall([A,B,C], (between(1,N,A), between(A,N,B), between(B,N,C), A**2 + B**2 == C**2)). % pyth2 with symmetry breaking (A < B) pyth3(N) = findall([A,B,C], (member(A,1..N), member(B,1..N), member(C,1..N), A < B, A**2 + B**2 == C**2)).