Previous | Next →

While useful, the previously mentioned features still don’t get very far beyond basic calculation needs. The one feature that turns Objective Caml into a highly expressive tool is functions. A function follows the mathematical tradition of being a mapping: it associates every element of a set with an element from another set. The element from the first set is the argument, and the element from the other set is the return value.

To call a function, you provide it with an argument and it is automatically turned into its return value for that argument. For example, the function “string_of_int” returns a bit of text representing an integer, so you could use it like so:

string_of_int 10

This would evaluate to the text “10″.

How do we define functions? Well, we simply write an expression which uses the argument and evaluates to the return value. Of course, the function doesn’t know the value of its argument until it’s called. So, when we write the function’s code, we use a placeholder name to represent the argument: this variable is called the parameter, and it is replaced with the argument itself when the function is called. The syntax is:

fun (parameter) -> (expression)

For instance, a function that adds two to a number can be defined as:

fun x -> x + 2

It is not very useful as such, so let’s give it a name and call it:

let add = fun x -> x + 2 ;;
add 3 * add 4

This evaluates to 5 * 6 = 30, and illustrates the main point of functions: they allow you to describe an operation once, and use it in many places simply by using the function’s name.

The Objective Caml language provides two shortcuts for defining functions. The first was designed to write functions that returns functions. Suppose that I write:

fun x -> (fun y -> x + y)

This can be elegantly shortened to:

fun x y -> x + y

The second shortcut was designed to make the definition of named functions easier. Suppose that I write:

let add = fun x -> x + 2

This can be elegantly shortened to:

let add x = x + 2

The two shortcuts can be combined, so that:

let add x y = x + y

Means the same as:

let add = fun x -> (fun y -> x+y)

Previous | Next →

0 Responses to “Functions”


  1. No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



1208 feed subscribers
(readers who polled a feed this week)