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 18. Subtyping

In the previous chapter we introduced the multiple dispatch mechanism and polymorphic methods. Not specifying the types of the arguments results in a method that can be called with arguments of any type. Specifying a subset of allowed types in the signature of a method is a logical next step.

In this chapter I demonstrate subtyping using types that represent playing cards, decks of cards, and poker hands.

If you don’t play poker, you can read about it, but you don’t have to; I’ll tell you what you need to know for the exercises.

Cards

There are 52 cards in a deck, each of which belongs to one of 4 suits and one of 13 ranks. The suits are Spades (), Hearts (), Diamonds (), and Clubs (). The ranks are Ace (A), 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack (J), Queen (Q), and King (K). Depending on the game that you are playing, an Ace may be higher than a King or lower than a 2.

If we want to define a new object to represent a playing card, it is obvious what the attributes should be: rank and suit. It is not as obvious what type the attributes should be. One possibility is to use strings containing words like "Spade" for suits and "Queen" for ranks. One problem with this implementation is that it would not be easy to compare cards to see which had a higher rank or suit.

An alternative is to use integers to encode the ranks and suits. In this context, “encode” means that we are going to define a mapping between numbers and suits, or between numbers and ranks. This ...

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