Concepts of Programming Languages

(Sean Pound) #1

15.9 F# 713


defines y to be a very long sequence, but only the needed elements are gener-
ated. For display, only the first four are generated.


let y = seq {0..100000000};;
y;;
val it: seq = seq[0; 1; 2; 3;.. .]


The first line above defines y; the second line requests that the value of y be
displayed; the third is the output of the F# interactive interpreter.
The default step size for integer sequence definitions is 1 , but it can be
set by including it in the middle of the range specification, as in the following
example:


seq {1..2..7};;


This generates seq [1; 3; 5; 7].
The values of a sequence can be iterated with a for-in construct, as in
the following example:


let seq1 = seq {0..3..11};;
for value in seq1 do printfn "value = %d" value;;


This produces the following:


value = 0
value = 3
value = 6
value = 9


Iterators can also be used to create sequences, as in the following example:

let cubes = seq {for i in 1..5 −> (i, i i i)};;


This generates the following list of tuples:


seq [(1, 1); (2, 8); (3, 27); (4, 64); (5, 125)]


This use of iterators to generate collections is a form of list comprehension.
Sequencing can also be used to generate lists and arrays, although in these
cases the generation is not lazy. In fact, the primary difference between lists
and sequences in F# is that sequences are lazy, and thus can be infinite, whereas
lists are not lazy. Lists are in their entirety stored in memory. That is not the
case with sequences.
The functions of F# are similar to those of ML and Haskell. If named, they
are defined with let statements. If unnamed, which means technically they are

Free download pdf