This project is read-only.
Declaring and calling inner functions

Category:
Functions
Description: Declaring and calling functions within the body of another function
Code:
let FunctionSample1() =
let twice x = x + x
printfn "twice 2 = %d" (twice 2)
printfn "twice 4 = %d" (twice 4)
printfn "twice (twice 2) = %d" (twice (twice 2))

Execution Result:
twice 2 = 4
twice 4 = 8
twice (twice 2) = 8

Declaring and calling inner functions

Category:
Functions
Description: Declaring and calling functions within the body of another function
Code:
let FunctionSample2() =
let even n = (n%2 = 0)
let tick x = printfn "tick %d" x
let tock x = printfn "tock %d" x
let choose f g h x = if f x then g x else h x
let ticktock = choose even tick tock // ticktock is a function built out of other functions using 'choose'
for i = 0 to 10 do
ticktock i


Execution Result:
tick 0
tock 1
tick 2
tock 3
tick 4
tock 5
tick 6
tock 7
tick 8
tock 9
tick 10

Declaring and calling anonymous function lamda expressions

Category:
Functions
Description: Introduction to using lambda expressions
Code:
let FunctionSample3() =
let tick x = printfn "tick %d" x
let tock x = printfn "tock %d" x
let choose f g h x = if f x then g x else h x
for i = 0 to 10 do
// This is like the previous sample, but uses an anonymous lambda expression for
// the function that decides whether to tick or tock.
choose (fun n -> n%2 = 0) tick tock i

//--------------------------------------------------------

Execution Result:
tick 0
tock 1
tick 2
tock 3
tick 4
tock 5
tick 6
tock 7
tick 8
tock 9
tick 10

Last edited Sep 13, 2011 at 12:35 AM by ttliu2000, version 1

Comments

No comments yet.