Functional Programming

Distance Course (1dl027)
Uppsala University, Sweden

Assignment 1

A. Type Inference, Reduction, and Currying

Consider the following SML declarations:
fun mystery x = ((fn y => y-1) x) * ((fn y => y+1) x) + 1
fun triple g z = (1+1) * g z
Answer the following sub-questions:
  1. Reverse-engineer the specifications of mystery and triple. Assume that mystery has no pre-condition and that the pre-condition on triple is that its function argument must be defined on the 'other' argument. Simplify the post-conditions as much as possible.
  2. Give the SML value declaration that is equivalent to the SML function declaration of triple above.
  3. Explain what happens when the SML declaration val strange = triple mystery is entered.
  4. Step-by-step reduce the SML expression strange 4. Use the same style as in slide 2.17.

B. Divisibility and primes

Give SML declarations for the following functions:
  1. notDivisor(d, n) . Returns true if (and only if) d is not a divisor of n.

    For example, notDivisor(2, 5) should return true and notDivisor(3, 9) should return false

  2. test_d(a, b, c). Returns true if
    notDivisor(a, c),
    notDivisor(a+1, c),
    ...
    notDivisor(b, c)
    are all true.

    For example, test_d(2,5,13) is true and test_d(5, 12, 22) is false (since 11 divides 22).

    You must decide how to handle the case when a > b.

  3. prime(n). Returns true if n is a prime number (n is not equal to 1 and no other natural number except 1 divides n).
  4. For example, prime(12) should return false and prime(13) should return true.

C. Integer Sets

Finite integer sets can be represented by increasingly ordered lists of integers. For example, the set {91, 11, 17} would be represented by the list [11, 17, 91]. Using this representation, give SML declarations for the following value, and functions:
  1. empty: the empty set ∅
  2. insert x s: the set s ∪ {x}
  3. inter s1 s2: the set s1 ∩ s2
  4. diff s1 s2: the set s1 \ s2, that is the set of elements belonging to s1 but not to s2
  5. card s: the cardinality of the set s, that is the number of elements of s
  6. member x s: true if and only if x ∈ s
Exploit any pre-conditions to get more efficient functions.
Last modified: Thu Nov 8 11:47:28 MET 2007