Anonymous functions in F#

An anonymous function is a function which is not bound to an identifier and therefore has no name. In F# the fun keyword may be used to create an anonymous function.

fun x y -> x + y

 

Anonymous functions may be used as parameters for other functions. In such cases no identifiers are needed because the function is used in this context only. In a previous article I have shown you the concept of higher-order functions. I want to use this example to explain how to improve the source code by using anonymous functions.

The following source code shows the higher-order function which is used to create functions to increase, decrease and double up a value multiple times or to append whitespaces to a string.

let rec executeMultipleTimes(f,x,n) =
    if n = 0
    then x
    else f (executeMultipleTimes(f,x,n-1))

let increase x = x + 1
let decrease x = x - 1
let double x = 2 * x
let appendWhitespace x = x + " "

let increaseMultipleTimes(x,n) = executeMultipleTimes(increase,x,n)
let decreaseMultipleTimes(x,n) = executeMultipleTimes(decrease,x,n)
let doubleMultipleTimes(x,n) = executeMultipleTimes(double,x,n)
let appendWhitespaceMultipleTimes(x,n) = executeMultipleTimes(appendWhitespace,x,n)

 
As you can see the four functions increase, decrease, double and appendWhitespace have identifiers, but these identifiers are used only once. By using anonymous functions this not needed identifiers may be removed. The following source code shows the optimized example. The four anonymous functions are passed as parameters to the other functions.

let rec executeMultipleTimes(f,x,n) =
    if n = 0
    then x
    else f (executeMultipleTimes(f,x,n-1))

let increaseMultipleTimes(x,n) = executeMultipleTimes((fun x -> x + 1),x,n)
let decreaseMultipleTimes(x,n) = executeMultipleTimes((fun x -> x - 1),x,n)
let doubleMultipleTimes(x,n) = executeMultipleTimes((fun x -> 2 * x),x,n)
let appendWhitespaceMultipleTimes(x,n) = executeMultipleTimes((fun x -> x + " "),x,n)

 

Summary

Anonymous function may be used to improve the quality of your source code. They are very helpful, especially in situation where functions are used as parameters for other functions.

Advertisements
Dieser Beitrag wurde unter .NET, F# abgelegt und mit verschlagwortet. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s