CSCI305.github.io

CSCI 305 Programming Languages

ML Part 1

Reading: Webster Ch. 5

Instructions

  1. Install SML
    • For windows visit SourceForge and download either PolyML5.7.1-64bit.msi or PolyML5.7.1-32bit.msi
    • For MacOS follow the instructions here
    • For Ubuntu Linux based distros follow the instructions:
      • sudo apt-get install smlnj
  2. Watch This Video
  3. Review the Lecture Slides
  4. Review the Example Code
  5. Complete the Out of Class Exercise
  6. Check Your Learning
  7. Attend Class and Complete the In Class Exercises. Be sure to turn in Homework 1!
  8. Check Your Learning

Out of Class Exercise

Exercise 1

Write a function red3 of type 'a * 'b * 'c -> 'a * 'b that converts a tuple with three elements into one with two by eliminating the second element

Exercise 2

Write a function sqsum of type int -> int that takes a non-negative integer n and returns the sum of the squares of all the integers 0 through n. Your function need not behave well on inputs less than zero.

Check Your Learning:

Solution Video - (:)
Solution:

Exercise 1:

fun red3 (a, b, c) = (a, c);

Exercise 2:

fun sqsum n =
  if n = 0 then 0
  else (n * n) + sqsum (n - 1);

In Class Exercises

Exercise 1

Write a function cube of type int -> int that returns the cube of its parameter.

Exercise 2

Write a function pow of type real * int -> real that raises a real number to an integer power. Your function need not behave well if the integer power is negative.

Exercise 3

Write a function cycle1 of type 'a list -> 'a list whose output is the same as the input list, but with the first element of the list moved to the end. For example cycle1 [1,2,3,4] should return [2,3,4,1]

Exercise 4

Write a function min3 of type int * int * int -> int that returns the smallest of three integers.

Check Your Learning:

Solution:

Excercise 1:

fun cube n = n * n * n;

Excercise 2:

fun pow (x:real, n:int) =
  if n = 0 then 1.0
  else x * pow(x, n - 1);

Excercise 3:

fun cycle1 x =
  if null x then nil
  else (tl x) @ [hd x];

Exercise 4:

fun min3 (a, b, c) =
  if a <= b andalso a <= c then a
  else min3(b, c, a)