CS-460-1.Fall-2005:Homeworks:JayDonnellHomework
From CSWiki
[edit] Homework 1
% Get the last element of a list manually. This is just to practice manipulating lists without builtins
local Last ListIn Element in
ListIn = [1 2 3]
proc {Last ListIn ?Element}
case ListIn of Head|Tail then
if Tail == nil then
Element = Head
else
{Last Tail Element}
end
end
end
{Last ListIn Element}{Browse Element}
end
% Reverse a list manually.
local Rev ListIn ListOut in
ListIn = [1 2 3]
proc {Rev ListIn ?ListOut}
local L Laste Result NewLength ShortList in
if ListIn == nil then ListOut = nil
else
{Length ListIn L}
{Number.'-' L 1 NewLength}
if L == 1 then
ShortList = nil
{List.last ListIn Laste}
else
{List.take ListIn NewLength ShortList}
{List.last ListIn Laste}
end
{Rev ShortList Result}
ListOut = Laste|Result
end
end
end
{Rev ListIn ListOut} {Browse ListOut}
end
% Find the max element of a tree
local Insert T T2 T3 T4 TMax Out in
proc {Insert Key Value TreeIn ?TreeOut}
case TreeIn
of nil then TreeOut = tree(Key Value nil nil)
[] tree(K1 V1 T1 T2) then
if Key == K1 then TreeOut = tree(Key Value T1 T2)
elseif Key < K1 then T in
TreeOut = tree(K1 V1 T T2)
{Insert Key Value T1 T}
else T in
TreeOut = tree(K1 V1 T1 T)
{Insert Key Value T2 T}
end
end
end
proc {TMax Tr ?V}
{Browse 'in find'}
case Tr
of nil then V = nil
[] tree(K1 V1 T1 T2) then
if T2 == nil then V = V1
else
{TMax T2 V}
end
end
end
T = nil
{Insert 9 'jay' T T2}
{Insert 3 'bob' T2 T3}
{Insert 13 'zed' T2 T4}
{Browse T4}
{TMax T4 Out}
{Browse 'out'}
{Browse Out}
end
% Search a tree by key
local Insert T T2 T3 Find Out in
proc {Insert Key Value TreeIn ?TreeOut}
case TreeIn
of nil then TreeOut = tree(Key Value nil nil)
[] tree(K1 V1 T1 T2) then
if Key == K1 then TreeOut = tree(Key Value T1 T2)
elseif Key < K1 then T in
TreeOut = tree(K1 V1 T T2)
{Insert Key Value T1 T}
else T in
TreeOut = tree(K1 V1 T1 T)
{Insert Key Value T2 T}
end
end
end
proc {Find Tr K V}
{Browse 'in find'}
case Tr
of nil then V = nil
[] tree(K1 V1 T1 T2) then
if K == K1 then V = V1
elseif K < K1 then
{Find T1 K V}
else
{Find T2 K V}
end
end
end
T = nil
{Insert 9 'jay' T T2}
{Insert 3 'bob' T2 T3}
{Browse T3}
{Find T3 3 Out}
{Browse 'out'}
{Browse Out}
end

