

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Solutions to lab #09 of cs 3721: programming languages, focusing on imperative programming in ml using reference cells and loops. It includes instructions for creating reference cells, examples of reference cell usage, and the recursive and imperative versions of functions sum and gcd.
Typology: Lab Reports
1 / 3
This page cannot be seen from the preview
Don't miss anything!


CS 3721: Programming Languages Lab Lab #09 Solutions: Imperative Programming in ML
Due date: April 1, 3:30pm. At the beginning of the next recitation.
Goals of this lab:
ref v => creates a reference cell containig value v !r => dereferencing : returns the value contained in reference cell r r := v => places value v in reference cell r Reference cells correspond to the variables of C, Pascal and similar languages where as the value declarations that we have seen so far correspond to the constants of languages like C. Here are some examples:
let val x = ref 3.5; val y = ref 4.2; val z = ref 5. in x := (!x + !y * !x - !y) / !z; !x end;
=> val it = 2.74509803922 : real
(b) Define a reference cell nameList which initially has empty list as its value. Then, add your first and last name to this list using the cons operator ā::ā. The final value of the reference cell should be [āfirstNameā, ālastNameā]. Return the value of the reference cell.
Solution:
val nameList = ref ([]:( string list )); nameList := "baris" :: "tas" ::! nameList ; ! nameList ;
val i = ref 0; while !i < 10 do i := !i + 1;
Now, write both recursive and imperative versions of the function sum that computes the expres- sion,
ā^ n
i= 1
i. The function takes one argument which is n in the summation. (Use let, while, and
reference cells in the imperative version.) Test your functions with the following:
(a) Purely functional version: Solution:
fun sum(n) = if n = 1 then 1 else n + sum(n -1);
(b) Imperative version: Solution:
fun sum(n) = let val i = ref 1; val total = ref 0; in while !i<=n do ( total := !total + !i; i := !i + 1 ); !total end;