Basic List Construction 2

Category:
Lists, Tuples and Options
Description: This sample demonstrates a simple generative list comprehension to specify lists
Code:
let SequenceExpressionSample1() =

let data1 = [ for x in 0..20 -> x, x * x ]

// This uses a nested loop
let data2 = [ for x in 0..5 do
for y in 0..5 do
yield x, y, x * y ]

// This uses a filter
let data3 = [ for x in 0..5 do
for y in 0..5 do
if x > y then
yield (x, y, x * y) ]

// This uses an internal let-binding
let data4 = [ for x in 0..5 do
for y in 0..5 do
if x > y then
let z = x * y
yield (x, y, z) ]

printfn "data1 = \n%A\n\n" data1
printfn "data2 = \n%A\n\n" data2
printfn "data3 = \n%A\n\n" data3
printfn "data4 = \n%A\n\n" data4

Execution Result:
data1 = 
[(0, 0); (1, 1); (2, 4); (3, 9); (4, 16); (5, 25); (6, 36); (7, 49); (8, 64);
(9, 81); (10, 100); (11, 121); (12, 144); (13, 169); (14, 196); (15, 225);
(16, 256); (17, 289); (18, 324); (19, 361); (20, 400)]


data2 =
[(0, 0, 0); (0, 1, 0); (0, 2, 0); (0, 3, 0); (0, 4, 0); (0, 5, 0); (1, 0, 0);
(1, 1, 1); (1, 2, 2); (1, 3, 3); (1, 4, 4); (1, 5, 5); (2, 0, 0); (2, 1, 2);
(2, 2, 4); (2, 3, 6); (2, 4, 8); (2, 5, 10); (3, 0, 0); (3, 1, 3); (3, 2, 6);
(3, 3, 9); (3, 4, 12); (3, 5, 15); (4, 0, 0); (4, 1, 4); (4, 2, 8); (4, 3, 12);
(4, 4, 16); (4, 5, 20); (5, 0, 0); (5, 1, 5); (5, 2, 10); (5, 3, 15);
(5, 4, 20); (5, 5, 25)]


data3 =
[(1, 0, 0); (2, 0, 0); (2, 1, 2); (3, 0, 0); (3, 1, 3); (3, 2, 6); (4, 0, 0);
(4, 1, 4); (4, 2, 8); (4, 3, 12); (5, 0, 0); (5, 1, 5); (5, 2, 10); (5, 3, 15);
(5, 4, 20)]


data4 =
[(1, 0, 0); (2, 0, 0); (2, 1, 2); (3, 0, 0); (3, 1, 3); (3, 2, 6); (4, 0, 0);
(4, 1, 4); (4, 2, 8); (4, 3, 12); (5, 0, 0); (5, 1, 5); (5, 2, 10); (5, 3, 15);
(5, 4, 20)]



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

Comments

No comments yet.