[LEFT] [FONT=monospace] let rec factorial n =
match n with
| 0I -> 1I
| _ -> n * factorial (n - 1I)
[/FONT]
[/LEFT]
[LEFT] [FONT=monospace] open List
(* print a list of numbers recursively *)
let rec printlist lst =
if lst <> [] then
printf "%d\n" (nth lst 0)
printlist (tl lst)
(* Same thing, using matching against list elements *)
let rec printlist2 l =
match l with
| [] -> ()
| h :: t -> printfn "%A" h
printlist2 t
(* Using shorthand for match *)
let rec printlist3 = function
| [] -> ()
| h :: t -> printfn "%A" h
printlist3 t
(* Or, using a higher-order function *)
let printlist4 lst = List.iter (printfn "%A") lst
[/FONT]
[/LEFT]
[LEFT] [FONT=monospace] (* Fibonacci Number formula *)
let rec fib n =
match n with
| 0 | 1 -> n
| _ -> fib (n - 1) + fib (n - 2)
(* An alternative approach - a lazy recursive sequence of Fibonacci numbers *)
let rec fibs = seq {
yield! [1; 1];
for (x, y) in Seq.zip fibs (Seq.skip 1 fibs) -> x + y }
(* Print even fibs *)
[1 .. 10]
|> List.map fib
|> List.filter (fun n -> (n % 2) = 0)
|> printlist
(* Same thing, using Comprehension syntax *)
[ for i in 1..10 do
let r = fib i
if r % 2 = 0 then yield r ]
|> printlist
[/FONT]
[/LEFT]
[LEFT] [FONT=monospace] (* Sample Windows Forms Program *)
(* We need to open the Windows Forms library *)
open System.Windows.Forms
(* Create a window and set a few properties *)
let form = new Form(Visible=true, TopMost=true, Text="Welcome to F#")
(* Create a label to show some text in the form *)
let label =
let temp = new Label()
let x = 3 + (4 * 5)
(* Set the value of the Text*)
temp.Text <- sprintf "x = %d" x
(* Remember to return a value! *)
temp
(* Add the label to the form *)
do form.Controls.Add(label)
(* Finally, run the form *)
[<STAThread>]
do Application.Run(form)
[/FONT]
[/LEFT]
[LEFT] [FONT=monospace] (* async workflows sample (parallel tasks) *)
(* very naive prime number detector *)
let is_prime (n:int) =
let bound = int (System.Math.Sqrt(float n)) in
{2 .. bound} |> Seq.exists (fun x -> n % x = 0) |> not
(* we are using async workflows *)
let primeAsync n =
async { return (n, is_prime n) }
(* return primes between m and n using multiple threads *)
let primes m n =
{m .. n}
|> Seq.map primeAsync
|> Async.Parallel
|> Async.RunSynchronously
|> Array.filter snd
|> Array.map fst
(* run a test *)
primes 1000000 1002000
|> Array.iter (printfn "%d")
[/FONT]
[/LEFT]