// Add a slot called myAverage to a list that computes the average // of all the numbers in a list. What happens if there are no // numbers in a list? (Bonus: Raise an Io exception if any item in // the list is not a number). // Define the myArray method on the core List object. // // NOTE: We could have just used sum()/size() to accomplish the same // thing, including the Io exception which will get raised when any // non-numeric value is included in a sum() message. However, for // practice sake, I will perform this a little bit more manually. List myAverage := method( // Check to see if we have any values in our list. If not, // return nil. if( (self size() == 0), return( nil ); ); // At this point, we know we have at least one value to average. // As such, let's prepare our running total. runningSum := 0; // Loop over each value in the list. self foreach( index, value, // Check to see if the current value is a number. If not, // we are going to raise an exception. if( (value type() != "Number"), // Raise an exception. As part of our error message, we // are reflectively adding the method name (so we don't // have to hardcode it in the error). Exception raise( "NonNumericValue", ("A non-numeric value [" .. value .. "] was encountered during the " .. (call message() name()) .. " operation.") ); ); // If no exception was raised, we can add this numeric value // to our running sum. runningSum = (runningSum + value); ); // Return the average of the sum over the size of the array. return( runningSum / (self size()) ); ); // ---------------------------------------------------------- // // ---------------------------------------------------------- // // Try it once with no values. list() myAverage() println(); // Try it once with only valid numbers. list( 1, 2, 3, 4, 5 ) myAverage() println(); // Try it once with invalid values. list( 1, 2, "Dang!", 4, 5 ) myAverage() println();