Concepts of Programming Languages

(Sean Pound) #1

714 Chapter 15 Functional Programming Languages


lambda expressions, they are defined with the fun reserved word. The follow-
ing lambda expression illustrates their syntax:

(fun a b −> a / b)

Note that there is no difference between a name defined with let and a
function without parameters defined with let.
Indentation is used to show the extent of a function definition. For example,
consider the following function definition:

let f =
let pi = 3.14159
let twoPi = 2.0 * pi
twoPi;;

Note that F#, like ML, does not coerce numeric values, so if this function
used 2 in the second-last line, rather than 2.0, an error would be reported.
If a function is recursive, the reserved word rec must precede its name in
its definition. Following is an F# version of factorial:

let rec factorial x =
if x <= 1 then 1
else n * factorial(n − 1)

Names defined in functions can be outscoped, which means they can be
redefined, which ends their former scope. For example, we could have the
following:

let x4 x =
let x = x * x
let x = x * x
x;;

In this function, the first let in the body of the x4 function creates a new ver-
sion of x, defining it to have the value of the square of the parameter x. This
terminates the scope of the parameter. So, the second let in the function body
uses the new x in its right side and creates yet another version of x, thereby
terminating the scope of the x created in the previous let.
There are two important functional operators in F#, pipeline (|>) and
function composition (>>). The pipeline operator is a binary operator that
sends the value of its left operand, which is an expression, to the last parameter
of the function call, which is the right operand. It is used to chain together
function calls while flowing the data being processed to each call. Consider the
following example code, which uses the high-order functions filter and map:

let myNums = [1; 2; 3; 4; 5]
let evensTimesFive = myNums
Free download pdf