Cleaning.
[Scala.git] / Assignment_07-FSharp / Assignment_07-FSharp / Program.fs
1 open System
2
3 // Question 1.
4 type Stack<'a> =
5 | Elem of 'a * Stack<'a>
6 | Empty
7 member this.Push a = Elem (a, this)
8 member this.Top =
9 match this with
10 | Elem (a, _) -> a
11 | Empty -> failwith "Empty stack!"
12 member this.Pop =
13 match this with
14 | Elem (_, rest) -> rest
15 | Empty -> failwith "Empty stack!"
16 override this.ToString () =
17 match this with
18 | Elem (e, rest) -> e.ToString() + "," + rest.ToString()
19 | Empty -> "Empty"
20
21 type Foo () = class end
22 type Bar () = inherit Foo ()
23
24 let question1 () =
25 printfn "Question 1"
26 let a = (((Empty.Push "hello").Push "world").Push "it's fun").Pop
27 printfn "a: %O" a
28 assert (a.ToString () = "world,hello,Empty")
29
30 let b = ((Empty.Push 1).Push 3)
31 printfn "b.Top: %O" b.Top
32 assert (b.Top = 3)
33
34 let c : Stack<Bar> = (Empty.Push <| Bar ()).Push <| Bar ()
35 c.Top :> Bar |> ignore
36 c.Top :> Foo |> ignore
37
38 let d : Stack<#Foo> = (Empty.Push <| Bar ()).Push <| Bar ()
39 d.Top :> Bar |> ignore
40
41 // Question 4.
42 let question4 () =
43 let rec sieve sequence =
44 seq {
45 let h = Seq.head sequence
46 yield h
47 yield! sieve <| Seq.filter (fun m -> m % h <> 0) sequence
48 }
49 let primes = sieve <| (Seq.initInfinite id |> Seq.skip 2)
50 printfn "first primes: %A" <| (Seq.take 100 primes |> Seq.toList)
51
52 [<EntryPoint>]
53 let main argv =
54 question1 ()
55 question4 ()
56 0
57