FSharp Functional Programming—Anonymous Functions


Jump to: navigation, search
CSharp-Online.NET:Articles
.NET Articles

F# Functional Programming

© 2007 Robert Pickering

Anonymous Functions

F# provides an alternative way to define functions using the keyword fun; you can see this in the following example. Ordinarily, you would use this notation when it is not necessary to give a name to a function, so these are referred to as anonymous functions and sometimes called lambda functions or even just lambdas. The idea that a function does not need a name may seem a little strange, but if a function is to be passed as an argument to another function, then often you don’t need to give it a name of its own. I demonstrate this idea in the section “Lists” later in this chapter when you look at operations on lists. The arguments defined for this style of function can follow the same rules as when defining a function with a name, meaning that you can define the arguments so they can be partially applied or defined in the form of a tuple (see the section "Defining Types" later in this chapter for an explanation of tuples). The following example shows two functions that are created and then immediately applied to arguments so that the identifier x holds the result of the function rather than the function itself:

#light
let x = (fun x y -> x + y) 1 2

You can create an anonymous function with the keyword function. Creating functions this way differs from using the keyword fun since you can use pattern matching when using the keyword function (see the section "Pattern Matching" later in this chapter). Consequently, it can be passed only one argument, but you can do a couple of things if the function needs to have multiple parameters. The first line of the following example shows a function using the function keyword written so the function can be partially applied, meaning the arguments can be passed one at a time if needed. The second line shows a function defined using the function keyword that takes a tuple argument.

let x1 = (function x -> function y -> x + y) 1 2
let x2 = (function (x, y) -> x + y) (1, 2)

The keyword fun is generally preferred when defining anonymous functions because it is more compact; you can see this is the case when browsing the source for the libraries and examples distributed with F#.


Previous_Page_.gif Next_Page_.gif




Personal tools

AbeBooks.com – Textbooks