Concepts of Programming Languages

(Sean Pound) #1

428 Chapter 9 Subprograms


Arithmetic operators are examples of type-constrained operations. For exam-
ple, consider the following function definition:

let adder x y = x + y;;

Type inferencing sets the type of x and y and the return value to int. Because
there is no type coercion in F#, the following call is illegal:

adder 2.5 3.6;;

Even if the type of the parameters were set to be generic, the + operator would
cause the types of x and y to be int.
The generic type could also be specified explicitly in angle brackets, as in
the following:

let printPair2<'T> x y =
printfn "%A %A" x y;;

This function must be called with a type,^10 as in the following:

printPair2<float> 3.5 2.4;;

Because of type inferencing and the lack of type coercions, F# generic
functions are far less useful, especially for numeric computations, than those
of C++, Java 5.0+, and C# 2005+.

9.10 Design Issues for Functions


The following design issues are specific to functions:


  • Are side effects allowed?

  • What types of values can be returned?

  • How many values can be returned?


9.10.1 Functional Side Effects


Because of the problems of side effects of functions that are called in expressions,
as described in Chapter 5, parameters to functions should always be in-mode
parameters. In fact, some languages require this; for example, Ada functions can
have only in-mode formal parameters. This requirement effectively prevents a
function from causing side effects through its parameters or through aliasing of
parameters and globals. In most other imperative languages, however, functions


  1. Cconvention explicitly states that generic types are named with uppercase letters starting at T.

Free download pdf