Chapter 16. Structs and Functions
Now that we know how to create new composite types, the next step is to write functions that take programmer-defined objects as parameters and return them as results. In this chapter I also present the “functional programming style” and two new program development plans.
Time
As another example of a composite type, we’ll define a struct called MyTime that records the time of day. The struct definition looks like this:
"""Represents the time of day.fields: hour, minute, second"""structMyTimehourminutesecondend
The name Time is already used in Julia, so I’ve chosen this name to avoid a name clash. We can create a new MyTime object as follows:
julia>time=MyTime(11,59,30)MyTime(11, 59, 30)
The object diagram for the MyTime object looks like Figure 16-1.
Figure 16-1. Object diagram
Exercise 16-1
Write a function called printtime that takes a MyTime object and prints it in the form hour:minute:second. The @printf macro of the standard library module Printf prints an integer with the format sequence "%02d" using at least two digits, including a leading zero if necessary.
Exercise 16-2
Write a Boolean function called isafter that takes two MyTime objects, t1 and t2, and returns true if t1 follows t2 chronologically and false otherwise. Challenge: don’t use an if statement.
Pure Functions
In the next few sections, we’ll write two ...