Courses/CS 460/Fall 2005/Homework/Duc Trinh/Oct 1
From CSWiki
Contents |
[edit] Homework 1
Comments / Notes / Questions:
- All my examples are for list. I couldn't figure out the binary tree.
[edit] InTheList
% returns a yes if a specified element is in the list
declare fun {InTheList List A B}
case List of H|T then
if (H==A) then
B=yes
else if T \= nil then
{InTheList T A B}
else
B=no
end
end
end
end
local List1 X Y in
List1 = [1 2 3 4 5 6]
X = 6
{Browse {InTheList List1 X Y}}
end
[edit] GetElementUpToIndex
% Return a list up to a specified index from the original list.
declare fun {GetElementUpToIndex List3 Index}
case List3 of H|T then
if (Index > 0) then
H | {GetElementUpToIndex T Index-1}
else
nil
end
[] nil then nil
end
end
local X in
X = [11 2 3 38 99 37 38 22]
{Browse {GetElementUpToIndex X 4}}
end
[edit] GetSumOfElements and GetAverage
% Get the sum of elements in a list consisting of numbers only.
declare fun {GetSumOfElements List}
case List of H|T then
if T \= nil then
H + {GetSumOfElements T}
else
H
end
end
end
% Get the average for elements in a list consisting of numbers only.
declare fun {GetAverage List2}
{GetSumOfElements List2} div {Length List2}
end
local X in
X = [11 2 3 38 99 37 38 22]
{Browse {GetSumOfElements X}}
{Browse {GetAverage X}}
end

