Download Mosel user guide

Transcript
model Prime
parameters
LIMIT=100
end-parameters
! Search for prime numbers in 2..LIMIT
declarations
SNumbers: set of integer
SPrime: set of integer
end-declarations
! Set of numbers to be checked
! Set of prime numbers
SNumbers:={2..LIMIT}
writeln("Prime numbers between 2 and ", LIMIT, ":")
n:=2
repeat
while (not(n in SNumbers)) n+=1
SPrime += {n}
! n is a prime number
i:=n
while (i<=LIMIT) do
! Remove n and all its multiples
SNumbers-= {i}
i+=n
end-do
until SNumbers={}
writeln(SPrime)
writeln(" (", getsize(SPrime), " prime numbers.)")
end-model
This example uses a new function, getsize, that if applied to a set returns the number of
elements of the set. The condition in the while loop is the logical negation of an expression,
marked with not: the loop is repeated as long as the condition n in SNumbers is not satisfied.
8.2.1
Set operators
The preceding example introduces the operator += to add sets to a set (there is also an operator
-= to remove subsets from a set). Another set operator used in the example is in denoting
that a single object is contained in a set. We have already encountered this operator in the
enumeration of indices for the forall loop.
Mosel also defines the standard operators for comparing sets: subset (<=), superset (>=), difference (<>), end equality (=). Their use is illustrated by the following example:
model "Set comparisons"
declarations
RAINBOW = {"red", "orange", "yellow", "green", "blue", "purple"}
BRIGHT = {"yellow", "orange"}
DARK = {"blue", "brown", "black"}
end-declarations
writeln("BRIGHT is included in RAINBOW:
writeln("RAINBOW is a superset of DARK:
writeln("BRIGHT is different from DARK:
writeln("BRIGHT is the same as RAINBOW:
",
",
",
",
BRIGHT <= RAINBOW)
RAINBOW >= DARK)
BRIGHT <> DARK)
BRIGHT = RAINBOW)
end-model
As one might have expected, this example produces the following output:
BRIGHT is included in RAINBOW: true
Sets
46
Mosel User Guide