10 User-defined operators for derived types

 

This chapter covers

  • User-defined operators for derived types
  • Writing a minimal countdown app
  • Validating user input
  • Synchronization on assignment in the tsunami simulator

Almost any app working with real-world data, or any program more complex than a toy model, will use derived types (classes) to handle abstract data. Operators for arithmetic (+, -, *, /, **) and comparison (==, /=, >=, <=, >, <) are available out of the box for built-in numeric types (integer, real, complex), but not for derived types. For example, to keep track of the calendar date and time in an app, you’d need to compare, add, and subtract datetime instances (data structures that represent date and time). This is where derived types from chapter 8 and generic procedures and custom operators from chapter 9 come together to form a powerful feature of the language: user-defined operators for derived types. Combining these two capabilities will allow you to define what the built-in (and custom) operators mean for any derived type, and in a way extend the syntax of the language.

10.1 Happy Birthday! A countdown app

10.1.1 Some basic specification

10.1.2 Implementation strategy

10.2 Getting user input and current time

10.2.1 Your first datetime class

10.2.2 Reading user input

10.2.3 Getting current date and time

10.3 Calculating the difference between two times

10.3.1 Modeling a time interval

10.3.2 Implementing a custom subtraction operator

10.3.3 Time difference algorithm

10.3.4 The complete program

10.4 Overriding operators in the tsunami simulator

10.4.1 A refresher on the Field class

10.4.2 Implementing the arithmetic for the Field class

10.4.3 Synchronizing parallel images on assignment