Skip to Main Content
Think Julia
book

Think Julia

by Ben Lauwens, Allen B. Downey
April 2019
Beginner content levelBeginner
295 pages
5h 48m
English
O'Reilly Media, Inc.
Content preview from Think Julia

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
"""
struct MyTime
    hour
    minute
    second
end

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.

thju 1601
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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Julia

Practical Julia

Lee Phillips
Getting Clojure

Getting Clojure

Russ Olsen
Learning Go

Learning Go

Jon Bodner

Publisher Resources

ISBN: 9781492045021Errata PageSupplemental Content