Courses/CS 460/Fall 2005/Homework/Joey Leung/Oct 8
From CSWiki
< Courses | CS 460 | Fall 2005 | Homework | Joey Leung
Contents |
[edit] 5 Recursive Methods
[edit] Last
declare Last in
local Y in
proc {Last X}
case X of H|T then
if T==nil then Y=H
else {Last T}
end
end
end
{Browse Y}
end
{Last [a b c d e]} --> e
[edit] Length
declare
fun {Length L}
if L==nil then 0
else case L of H|T then {Length T} +1 end end
end
{Browse {Length [1 2 3 0]}} --> 4
% another version of Length
declare Length in
proc {Length L}
local LengthHelper in
fun {LengthHelper LL}
if LL==nil then 0
else case LL of H|T then {LengthHelper T} +1 end
end
end
{Browse {LengthHelper L}}
end
end
{Length [0 1 2 3 4]} --> 5
declare Length in
proc {Length L}
local LengthHelper Out in
proc {LengthHelper LL Ans}
local X in
case LL of H|T then
if T==nil then Ans=1
else {LengthHelper T X} Ans=1+X
end
end
end
end
{LengthHelper L Out}
{Browse Out}
end
end
{Length [1 1 1 1 1 1]} --> 6
[edit] Nth
declare
fun {Nth L Num}
case L of H|T then
if Num==1 then H
else {Nth T Num-1}
end
end
end
{Browse {Nth [1 2 3 4] 3}} --> 3
declare Nth in
proc {Nth L Num}
local NthHelper in
fun {NthHelper L2 Num2}
case L2 of H|T then
if Num2==1 then H
else {NthHelper T Num2-1}
end
end
end
{Browse {NthHelper L Num}}
end
end
{Nth [1 2 3 4 5] 4} --> 4
[edit] Reverse
declare
local Reverse in
fun {Reverse L}
case L of H|T then {Reverse T}|H
else nil
end
end
end
{Browse {Reverse [1 2 3 4 5]}} --> [5 4 3 2 1]
% Don't know why this isn't working, it is the same as above!!
declare
proc {Reverse L}
local ReverseHelper in
fun {ReverseHelper L2}
case L2 of H|T then {ReverseHelper T}|H
else nil
end
end
{Browse {ReverseHelper L}}
end
end
{Reverse [1 2 3 4 5]} --> ((((nil|5)|4)|3)|2)|1
declare
proc {Reverse L}
local ReverseHelper in
fun {ReverseHelper L2}
case L2 of H|T then {Append {ReverseHelper T} [H]}
else nil
end
end
{Browse {ReverseHelper L}}
end
end
{Reverse [1 2 3 4 5]} --> [5 4 3 2 1]
[edit] Non-recursive version of merge-sort
declare
fun {Singleton L}
L|nil
end
declare
fun {Convert L}
if L==nil then nil
else case L of H|T then {Singleton H}|{Convert T} end
end
end
{Browse {Convert [1 2 3]}} --> [[1] [2] [3]]
% Another way to write Convert
declare
fun {Convert L}
if L==nil then nil
else local X in
case L of H|T then X=H|nil X|{Convert T} end
end
end
end
{Browse {Convert [1 2 3]}} --> [[1] [2] [3]]
declare
fun {Merge L}
case L of H|T then
if L==nil then nil
else if T==nil then H|nil
else case T of A|B then
if B==nil then {Append H A}|nil
else {Append H A}|{Merge B} end
end
end
end
end
end
{Browse {Merge [[1]]}} --> [[1]]
{Browse {Merge [[1] [2]]}} --> [[1 2]]
{Browse {Merge [[1] [2] [3]]}} --> [[1 2] [3]]

