CSCI305.github.io

CSCI 305 Programming Languages

ML Part 3

Reading: Webster Ch. 9

Instructions

  1. Watch This Video - (10:13)
  2. Watch This Video - (09:04)
  3. Watch This Video - (14:06)
  4. Watch This Video - (16:55)
  5. Review the Lecture Slides
  6. Review the Example Code
  7. Complete the Out of Class Exercise
  8. Check Your Learning
  9. Attend Class and Complete the In Class Exercises. Be sure to turn in Homework 2
  10. Check Your Learning

Out of Class Exercises

Exercise 1

Write a function il2rl of type int list -> real list that takes a list of integers and returns a list of the same numbers converted to type real. For example, if you evaluate il2rl [1,2,3] you should get [1.0,2.0,3.0]

Check Your Learning:

Solution:
fun il2rl x = map real x;

Exercise 2

Write a function band of type bool list -> bool that takes a list of boolean values and returns the logical AND of all of them. If the list is empty your function should return true

Check Your Learning:

Solution:
fun band x =
  let
    fun & (a, b) = a andalso b
  in
    foldr (op &) true x
  end;

In Class Exercises

Exercise 1

Write a function ordList of type char list -> int list that takes a list of characters and returns the list of the integer codes of those characters. For example, if you evaluate ordList [#"A", #"b", #"C"] you should get [65, 98, 67].

Check Your Learning:

fun ordList x = map ord x;
Solution:

Exercise 2

Write a function sqsum of type int list -> int that takes a list of integers and returns the sum of the squares of those integers. For example, if you evaluate squm [1,2,3,4] you should get 30

Check Your Learning:

Solution:
fun sqsum x = foldr (op +) 0 (map (fn x => x * x) x);

Exercise 3

Write a function append of type 'a list -> 'a list -> 'a list that takes two lists and returns the result of appending the second one onto the end of the first. For example, append [1,2,3] [4,5,6] should evaluate to [1,2,3,4,5,6]. Do not use the predefined appending utilities, like the @ operator or the concat function. Note that the function is curried.

Check Your Learning:

Solution:
fun append lst1 lst2 = foldr (op ::) lst2 lst1;

Exercise 4:

Write a function evens of type int list -> int list that takes a list of integers and returns the list of all the even elements from the original list (in the original order). For example, if you evaluate evens [1,2,3,4] you should get [2,4].

Check Your Learning:

Solution:
fun evens [] = []
|   evens (x::xs) =
      if x mod 2 = 0 then x::evens(xs)
      else evens(xs);