4.6.1 Method for encode-total-seconds

We can provide a method that converts from hours, minutes, and seconds to total seconds:

define method encode-total-seconds 	// 1
    (hours :: <integer>, minutes :: <integer>, seconds :: <integer>)	// 2
 => (total-seconds :: <integer>)	// 3
  ((hours * 60) + minutes) * 60 + seconds;	// 4
end method encode-total-seconds;	// 5

Line 2 contains the parameter list of the method encode-total-seconds. The method has three required parameters, named hours, minutes, and seconds, each of type <integer>. This method is invoked when encode-total-seconds is called with three integer arguments.

Line 3 contains the value declaration, which starts with the characters =>. It is a list declaring the values returned by the method. Each element of the list contains a descriptive name of the return value and the type of the value (if the type is omitted, it is <object>). In this case, there is one value returned, named total-seconds, which is of the type <integer>. The name of a return value is used purely for documentation purposes. Although methods are not required to have value declarations, there are advantages to supplying those declarations. When you provide a value declaration for a method, the compiler signals an error if the method tries to return a value of the wrong type, can check receivers of the results of the method for correct type, and can usually produce more efficient code. These advantages are significant, so we use value declarations throughout the rest of this book. For more information about value declarations, see Section 12.2.4, page 175.

Line 4 is the only expression in the body. It uses arithmetic functions to convert the hours, minutes, and seconds into total seconds. All methods return the value of the expression executed last in the body. This method returns the result of the arithmetic expression in line 4.

In line 5, we could have simply used end;. We provided end method decode-total-seconds; for documentation purposes. Throughout the rest of this book, we provide the extra words after the end of a definition.

We can call encode-total-seconds with arguments representing 8 hours, 30 minutes, and 59 seconds:

? encode-total-seconds(8, 30, 59);
30659

We find it convenient to call encode-total-seconds to initialize the total-seconds slot when we create an instance of <time-of-day>, or when we store a new value in that slot. Here, for example, we create a new instance:

? define variable *your-time-of-day* 
    = make(<time-of-day>, total-seconds: encode-total-seconds(8, 30, 59));

We examine the value of the total-seconds slot:

? *your-time-of-day*.total-seconds;
30659

The result reminds us that it would be useful to convert in the other direction as well — from total seconds to hours, minutes, and seconds.