Basic List Construction

Category:
Lists, Tuples and Options
Description: This sample demonstrates basic list construction
Code:
let ListConstruction() =

// Create an empty list
let emptyL = []

// Create a simple floating-point number list
let smallFloatsL = [1.0; 2.0; 3.0; 4.0]

// Create a list using a range expression - same rules as with arrays, step is optional
let listRngExp = [0..2..10]

// Create a list using a function based on index
let listByInit = List.init 5 (fun i -> i*i*i)

// Create a list using list comprehension
let listLC = [ for i in 1..5 do yield (i * 2) ]

// Another example of list comprehension
let listLC2 = [ for p in [(0,0); (1,1); (2,4); (3,9); (4,16); (5,25); (6, 36)] do
match p with
| (a,_) when a%2=0 -> yield p
| (_,_) -> () ]

printfn "emptyL = %A" emptyL
printfn "\nsmallFloatsL = %A" smallFloatsL
printfn "\nlistRngExp = %A" listRngExp
printfn "\nlistByInit = %A" listByInit
printfn "\nlistLC = %A" listLC
printfn "\nlistLC2 = %A" listLC2

Execution Result:
emptyL = []

smallFloatsL = [1.0; 2.0; 3.0; 4.0]

listRngExp = [0; 2; 4; 6; 8; 10]

listByInit = [0; 1; 8; 27; 64]

listLC = [2; 4; 6; 8; 10]

listLC2 = [(0, 0); (2, 4); (4, 16); (6, 36)]

Last edited Sep 14, 2011 at 2:48 AM by ttliu2000, version 1

Comments

No comments yet.