/
list_comprehensions.pi
55 lines (37 loc) · 1.64 KB
/
list_comprehensions.pi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
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)).