2 Questions for Programming Languages - Assignment 8 | CS 3723, Assignments of Programming Languages

Material Type: Assignment; Class: Programming Languages; Subject: Computer Science; University: University of Texas - San Antonio; Term: Spring 2008;

Typology: Assignments

Pre 2010

Uploaded on 07/30/2009

koofers-user-zjt-1
koofers-user-zjt-1 🇺🇸

10 documents

1 / 1

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Homework 8 (20pts)
Electronic submission due the end of Apr 1, 2008
Translate the following tail recursive function in ML to an equivalent implementation
using loops.
1. fun sum([], res) = res
| sum(x::y, res) = sum(y, x + res);
fun sum(input, res) =
let val p_input=ref input; val p_res=ref res
in while not (null (!p_input)) do
(p_res := hd(!p_input) + (!p_res); p_input:=tl(!p_input));
!p_res
end;
2. fun foo(x, y,z) = if (x < y) then foo(x+z, y,z)
else if (y < x) then foo(y,x,z-1) else y;
fun foo(x,y,z) =
let val p_x = ref x; val p_y = ref y; val p_z=ref z
in while not ((!p_x)=(!p_y)) do
if ((!p_x) < (!p_y)) then p_x := (!p_x) + (!p_z)
else if ((!p_y) < (!p_x)) then
let val tmp=(!p_x) in p_x:=(!p_y); p_y:=tmp; p_z := (!p_z)-1 end
else ();
!p_y
end;
1

Partial preview of the text

Download 2 Questions for Programming Languages - Assignment 8 | CS 3723 and more Assignments Programming Languages in PDF only on Docsity!

Homework 8 (20pts)

Electronic submission due the end of Apr 1, 2008

Translate the following tail recursive function in ML to an equivalent implementation using loops.

  1. fun sum([], res) = res | sum(x::y, res) = sum(y, x + res);

fun sum(input, res) = let val p_input=ref input; val p_res=ref res in while not (null (!p_input)) do (p_res := hd(!p_input) + (!p_res); p_input:=tl(!p_input)); !p_res end;

  1. fun foo(x, y,z) = if (x < y) then foo(x+z, y,z) else if (y < x) then foo(y,x,z-1) else y;

fun foo(x,y,z) = let val p_x = ref x; val p_y = ref y; val p_z=ref z in while not ((!p_x)=(!p_y)) do if ((!p_x) < (!p_y)) then p_x := (!p_x) + (!p_z) else if ((!p_y) < (!p_x)) then let val tmp=(!p_x) in p_x:=(!p_y); p_y:=tmp; p_z := (!p_z)-1 end else (); !p_y end;