Table of Contents
Dylan methods correspond roughly to the functions found in C and Pascal. They take zero or more named parameters, but also return zero or more named return values. A minimal Dylan method might look like the following:
define method hello-world() puts("Hello, world!"); end;
This method has no parameters and an unspecified return value. It could return any number of values of any type. In order to make the above code more clear, the function could be rewritten as follows:
define method hello-world() => (); puts("Hello, world!"); end method;
There have been two changes. The function now officially returns no value whatsoever. Also note that end has been replaced by end method which could in turn be rewritten as end method hello-world. In general, Dylan permits all the obvious combinations of keywords and labels to follow an end statement.
Dylan methods declare parameters in fashion similar to that of conventional languages, except for the fact that parameters may optionally be untyped. Both of the following methods are legal:
define method foo(x :: <integer>, y) end; define method bar(m, s :: <string>) end;
Both foo and bar have one typed and one untyped parameter, but neither has a well-defined return value (or actually does anything). As in C, each typed parameter must have its own type declaration; there's no syntax for saying “the last three parameters were all integers”.
Functions with variable numbers of parameters include the #rest keyword at the end of their parameter lists. Thus, the declaration for C's printf function would appear something like the following in Dylan:
define method printf(format-string :: <string>, #rest arguments) => (); // Print the format string, extracting // one at a time from "arguments". Note // that Dylan actually allows us to // verify the types of variables, // preventing those nasty printf errors, // such as using %d instead of %ld. // ... end method printf;
For an actual implementation of a lightweight printf function, see Appendix A.
Note that Dylan makes no provision for passing variables by reference in the Pascal sense, or for passing pointers to variables. parameter names are simply bound to whatever values are passed, and may be rebound like regular variables. This means that there's no way to write a swap function in Dylan (except by using macros). However, the following function works just fine, because it modifies the internal state of another object:
define method sell(car :: <car>, new-owner :: <string>) => (); if (credit-check(new-owner)) car.owner = new-owner; else error("Bad credit!"); end; end;
If this sounds unclear, reread the chapter on variables and expressions.