6 // Write something on a file.
7 let appendFile (filename
: string) (text
: string) =
8 use sw = new StreamWriter(filename
, true)
11 // Recursive function.
16 // Mutual recursive functions.
26 // Algebraic data type.
38 | NumCard of int * Suit
39 member this
.Value = // Property.
45 | NumCard (n, _
) when n >= 2 && n <= 10 -> n
46 | NumCard (_
) -> failwith
"Card has invalid value!"
50 for suit
in [ Spade; Club; Heart; Diamond ] do
56 yield
NumCard(n, suit
)
59 // Records with custom equality.
60 [<CustomEquality; NoComparison>]
62 { First: string; Last: string; Age: int }
63 override this.Equals(other
) =
65 | :? Person as p -> p.First = this.First && p.Last = this.Last
67 override this.GetHashCode() =
68 this.First.GetHashCode() ^^^ this.Last.GetHashCode()
70 let steve = { First = "Steve"; Last = "Holt"; Age = 17 }
71 let stevesTwin = { steve with First = "Paul" }
73 // Queries. Should be used with SQL or other external data sources.
74 let youngPersonNames persons
=
81 // Infinite lazy sequence.
84 for i
in 1 .. System.Int32.MaxValue do
95 yield
! [1; 2; 3] // Yields a collection.
99 Seq.unfold
(fun a -> if a > 10 then None else Some(10 * a, a + 1)) 1
101 // Functions composition.
103 let getFiles folder
=
104 Directory.GetFiles(folder
, "*.*", SearchOption.AllDirectories)
106 >> Array.map
(fun file
-> (new FileInfo(file
)).Length)
111 let Bill = "Bill Gates" // Must begin with a capital!
114 | Bill -> "Hello rich Bill!"
115 | name -> sprintf
"Hello poor %s" name
120 | a, b
when a <> b
-> true