MITTutorialApril2009: histExercise.fss

File histExercise.fss, 1.7 KB (added by sukyoungryu, 7 months ago)

File for Exercise 1 - 2 (Histogram)

Line 
1component histExercise
2import Set.{...}
3export Executable
4
5prime: Boolean[1000] = array1[\Boolean,1000\](true)
6upper = prime.bounds.upper
7
8removeMultiplesOf(p: ZZ32): () = do
9    prime[i] := false, i <- p^2 : upper : p
10end
11
12sieve() = do
13    prime[0] := false
14    prime[1] := false
15    prev: ZZ32 := 1
16    rootRoot = |/ SQRT SQRT upper \|
17    for p <- seq(2:rootRoot), prime[p] OR p = rootRoot do
18        for p' <- (prev^2 + 1):(p^2 - 1), prime[p'] do
19            removeMultiplesOf(p')
20        end
21        prev := p
22    end
23end
24
25(* Define a hist function.
26 * Given a set of primes, how many primes end with each digit?
27 *  Input: A set of primes
28 * Output: An array of size 10 where the i-th element of the array
29 *         denotes the number of primes ending with i
30 *
31 * Hint 1: ZZ32[10] denotes an array type of size 10 with elements of type ZZ32
32 * HInt 2: array1[\ZZ32,10\](0) creates a 1-dimensional array of size 10 with
33 *         elements of type ZZ32 initialized with 0.
34 * Hint 3: a set can be used as a generator in a for loop.
35 * Hint 4: MOD is a Fortress modulo operator.
36 *)
37hist(primes: Set[\ZZ32\]): ZZ32[10] =
38    fail("You still need to implement a hist function.")
39
40(**********************************************************************************
41 * TESTS
42 **********************************************************************************)
43
44run(): () = do
45    sieve()
46    result = hist {[\ZZ32\] p | (p, isPrime) <- prime.indexValuePairs, isPrime }
47    assert(result[0],  0)
48    assert(result[1], 40)
49    assert(result[2],  1)
50    assert(result[3], 42)
51    assert(result[4],  0)
52    assert(result[5],  1)
53    assert(result[6],  0)
54    assert(result[7], 46)
55    assert(result[8],  0)
56    assert(result[9], 38)
57    println("Your hist appears to work.")
58end
59
60end