Assignment #5
Original Deadline: Thursday, 1 December, 11:59 p.m.
Extended Deadline: Saturday, 3 December, 11:59 p.m.

General Instructions

All homework and programming exercises must be prepared in accordance with the instructions given in the Syllabus. Each assignment must be submitted to Blackboard by its stated deadline.

Elm Functions

Do the following programming exercises. You can put all the functions in the same Elm file.

  1. Write an Elm function sort3 that takes 3 integers and returns a 3-tuple with the values in descending order (i.e., largest first).

  2. Write an Elm function sumSqBig that takes 3 integers and returns the sum of the squares of the two larger integers. (You may use sort3.)

  3. Write a Elm function adjpairs that takes a polymorphic list and returns the list of all pairs of adjacent elements. For example, adjpairs [2,1,11,4] returns [(2,1), (1,11), (11,4)].

  4. Write an Elm function mean that takes a list of numbers and returns the mean (i.e., average) value for the list.

  5. Write an Elm function merge that takes two increasing lists of integers and merges them into a single increasing list (without any duplicate values). A list is increasing if every element is less than (<) its successors. Successor means an element that occurs later in the list, i.e., away from the head.

    Hint: For merge xs ys, you might want to consider a pattern match on (xs,ys).

  6. We can introduce a new Elm type for the natural numbers (i.e., nonnegative integers) with the definition

        type Nat = Zero | Succ Nat 

    where the constructor Zero represents the integer value 0 and constructor Succ represents the “successor function” from mathematics. Thus (Succ Zero) denotes 1, (Succ (Succ Zero)) denotes 2, and so forth. (See the natural number example on the lecture notes page that gives Lua, Java, Scala, Ruby, and Elixir versions.)

    We can define an Elm function natToInt that takes a Nat and returns the equivalent value of type Int as follows:

        natToInt : Nat -> Int
        natToInt n =
           case n of
              Zero   -> 0
              Succ n -> 1 + (natToInt n)

    Write the following Elm functions:

    1. intToNat that takes a nonnegative Int and returns the equivalent Nat, for example, 3 returns Succ (Succ (Succ Zero)).

    2. addNat that takes two Nat values and returns their sum as a Nat. This function cannot use the builtin integer or floating point addition.

    Extend the above example by doing ONE of the following:

    1. compNat that takes two Nat values and returns the value -1 if the first is less than the second, 0 if they are equal, and 1 if the first is greater than the second. This function cannot use the integer comparison operators.

    2. mulNat that takes two Nat values and returns their product as a Nat. This function cannot use the builtin integer or floating point operations. (Hint: You may want to use addNat.)

Comments