Courses/CS 460/Fall 2005/Homework/Duc Trinh/Oct 8
From CSWiki
Contents |
[edit] Homework 2
[edit] MyNth
% returns the Ith element of Xs (counting from 1).
declare fun {MyNth X I }
case X of H|T then
if (I == 1) then
H
else
{MyNth T I-1}
end
[] nil then nil
end
end
local X Y in
X = [123 32 23 1]
{Browse {MyNth X 3}}
end
[edit] MyNumber
%returns a list with elements from FromI to ToI with step StepI.
declare fun {MyNumber FromI ToI StepI}
if (StepI > 0)then
if (FromI + StepI =< ToI) then
FromI | {MyNumber FromI+StepI ToI StepI}
else if (FromI =< ToI) then
FromI
else
nil
end
end
else if (StepI < 0) then
if (FromI + StepI >= ToI) then
FromI | {MyNumber FromI+StepI ToI StepI}
else if (FromI >= ToI)then
FromI
else
nil
end
end
else
nil
end
end
end
{Browse {MyNumber 1 5 2}}
{Browse {MyNumber 5 1 2}}
{Browse {MyNumber 5 0 ~2}}
[edit] MySubtract
% Subtract leftmost occurrence of Y if there is one.
declare fun {MySubtract Xs Y}
case Xs of H|T then
if (H==Y) then
T
else
H | {MySubtract T Y}
end
[] nil then nil
end
end
local X in
X = [1 3 5 7 9]
{Browse {MySubtract X 0}}
end
[edit] MyZip
local List1 List2
proc {MyZip Xs Ys P ?Zs}
local C in
case Xs of Hx|Tx then
case Ys of Hy|Ty then
{P Hx Hy C}
Zs = C | {MyZip Tx Ty P}
[] nil then Zs=nil
end
[] nil then Zs=nil
end
end
end
in
List1 = [3 4 4 1]
List2 = [5 1 3 2]
{Browse {MyZip List1 List2 Max}}
end
[edit] MyTakeWhile and MyDropWhile
local Y
proc {MyTakeWhile Xs P ?Ys}
local L in
case Xs of H|T then
{P H L}
if L==true then
Ys=H
else
{MyTakeWhile T P ?Ys}
end
end
end
end
in
{MyTakeWhile [1 4 2 3 6 5] IsOdd Y} {Browse Y}
end
local Z
proc {MyDropWhile Xs P ?Zs}
local L in
case Xs of H|T then
{P H L}
if L==true then
Zs=T
else
{MyDropWhile T P ?Zs}
end
end
end
end
in
{MyDropWhile [ 1 4 2 3 6 5] IsOdd Z} {Browse Z}
end

