Basic Array Construction 2

Category:
Arrays, Hash Tables and Dictionaries
Description: This sample demonstrates more basic array construction.
Code:
let BasicConstruction2() =

// Create an array using a range expression
// general form: let = [|startExpr..[stepExpr]..endExpr|]
// where [stepExpr] is optional and has default value of 1
let arrRngExp = [|0..5|]

let arrRngExp2 = [|1..2..9|]

// Create an array using a function based on index
let squaresByInit = Array.init 5 (fun i -> (i, i*i))

// Create an array using array comprehension
let squaresByComp = [| for i in 0..5 do yield (i, i*i) |]

printfn "arrRngExp = %A" arrRngExp
printfn "\narrRngExp2 = %A" arrRngExp2
printfn "\nsquaresByInit = %A" squaresByInit
printfn "\nsquaresByComp = %A" squaresByComp

// Comprehensions can contain arbitrary code
let arbitraryComp =
[| for i in 1..10 do
if i <> 7 then
printfn "%d" i
yield i
printfn "did thru 10, skipped 7"
yield 100 |]


printfn "\narbitraryComp = %A" arbitraryComp

Execution Result:
arrRngExp = [|0; 1; 2; 3; 4; 5|]

arrRngExp2 = [|1; 3; 5; 7; 9|]

squaresByInit = [|(0, 0); (1, 1); (2, 4); (3, 9); (4, 16)|]

squaresByComp = [|(0, 0); (1, 1); (2, 4); (3, 9); (4, 16); (5, 25)|]
1
2
3
4
5
6
8
9
10
did thru 10, skipped 7

arbitraryComp = [|1; 2; 3; 4; 5; 6; 8; 9; 10; 100|]

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

Comments

No comments yet.