Home > Articles > Programming > Ruby

  • Print
  • + Share This
From the book

1.3 Function Basics

Let's go beyond the required definition of the main function and see how to define functions in D. Function definitions follow the model found in other Algol-like languages: first comes the return type, then the function's name, and finally the formal parameters1 as a parenthesized comma-separated list. For example, to define a function called fun that takes an uint and a double and returns an int, you'd write:

int fun(uint x, double y) {

Each function parameter (x and y in the example above) has, in addition to its type, an optional storage class that decides the way arguments are passed the function when invoked. By default, arguments are passed into fun by value. If storage class ref is prepended to parameter's type, the parameter is bound directly to the incoming argument such that changing the parameter is directly and immediately reflected in the value fun received from the outside. For example:

void fun(ref uint x, double y) {
   x = 42;
   y = 3.14;
void main() {
   uint a = 1;
   double b = 2;
   fun(a, b);
   writeln(a, " ", b);

This program prints 42 2 because x is a ref uint, meaning that assigning to x really means assigning to a. On the other hand, assigning to y has no effect on b because y is a private copy at fun's disposal.

The last adornments we'll discuss in this brief introduction are in and out. Simply put, in is a promise on the part of the function that it only wants to look, not touch, the parameter. Finally, using out with a function parameter works similarly to ref, with the amendment that the parameter is forcibly initialized to its default value upon function's entry. (Each type T defines an initial value, denoted as T.init. User-defined types can define their own init.)

There is a lot more to say about functions. You can pass functions to other functions; nest them into one another; allow a function to save its local environment (full-fledged syntactic closures); create and comfortably manipulate unnamed functions (lambdas); and some additional juicy little bits. We will get to each of these in good order.

  • + Share This
  • 🔖 Save To Your Account