2.3.2 Variables that have type constraints
We defined the variables *my-number* and *your-number* without giving a type constraint on the variables. Thus, we can store any type of value in these variables. For example, here we use the assignment operator, := , to store strings in these variables:
? *my-number* := "seven"; "seven" ? *your-number* := "twelve"; "twelve"
What happens if we try to add the string values stored in these variables?
? *my-number* + *your-number*;
ERROR: No applicable method for + with arguments ("seven", "twelve")
Dylan signals an error because the + function does not know how to operate on string arguments.
Environment note: The Dylan implementation defines the exact wording of error messages, and what happens when an error is signaled. If your implementation opens a Dylan debugger when an error is signaled, you now have an opportunity to experiment with the debugger! |
We can redefine the variables to include a type constraint, which ensures that the variables can hold only numbers. We specify that *my-number* can hold any integer, and that *your-number* can hold a single-precision floating-point number:
? define variable *my-number* :: <integer> = 7; ? define variable *your-number* :: <single-float> = 12.01;
What happens if we try to store a string in one of the variables?
? *my-number* := "seven"; ERROR: The value assigned to *my-number* must be of type <integer>
Both <integer> and <single-float> are classes. For now, you can think of a class as being like a datatype in another language. Dylan provides a set of built-in classes, and you can also define new classes.
Convention: Class names start with an open angle bracket and end with a close angle bracket — for example, |
The + function can operate on numbers of different types:
? *my-number* + *your-number*; 19.01




