NewtonScript Examples

Min Function

Let's create a function which takes an array of numbers and returns the minimum number. A QuickTime movie of this example is available.

First, we will create an empty frame to hold the function:

myFunctions := {};
#441734D  {}
Now we can make the function as a slot named Min in myFunctions:

myFunctions.Min := func(anArray)
begin
    local minSoFar := anArray[0];
    for i := 1 to Length(anArray) - 1 do
        if anArray[i] < minSoFar then
            minSoFar := anArray[i];
    return minSoFar;
end;
#4417D89  <function, 1 arg(s) #4417D89>
Test the function:

myFunctions:Min([5, 7, 3, 1, 10])
#4        1
As the function is written, it assumes that there is at least one element in the array. So what happens when we call it with an empty array? Why, we get an error, of course:

myFunctions:Min([])
   Index 0 out of bounds for object []
   evt.ex.fr;type.ref.frame
   -48205
So let's rewrite the function so that it will work even when we pass it an empty array. While we're at it, we'll take advantage of the foreach construct:

myFunctions.Min := func(anArray)
begin
    local minSoFar := nil;
    foreach element in anArray do
        if minSoFar = nil or element < minSoFar then
            minSoFar := element;
    return minSoFar;
end;
#441A031  <function, 1 arg(s) #441A031>
The first time through the loop, minSoFar is nil, and therefore element is assigned to minSoFar. Subsequent times though the loop, element is compared to minSoFar (element < minSoFar). Therefore, minSoFar holds the minimum element seen so far, or nil if no elements have been seen.

Let's test this function:

myFunctions:Min([5, 7, 3, 1, 10])
#4        1
What happens when we call it with an empty array? As we expect, we no longer get an error:

myFunctions:Min([])
#2        NIL

An online version of Programming for the Newton using Macintosh, 2nd ed. ©1996, 1994, Julie McKeehan and Neil Rhodes.

Last modified: 1 DEC 1996