Assignment 7
[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 printfn "%A" <|
36 match c.Top with
37 | :? Bar -> true
38 | _ -> false
39
40 let d : Stack<#Foo> = (Empty.Push <| Bar ()).Push <| Bar ()
41 printfn "%A" <|
42 match d.Top with
43 | :? Bar -> true
44 | _ -> false
45
46 // Question 4.
47 let question4 () =
48 let rec primesSieve sequence =
49 seq {
50 let h = Seq.head sequence
51 yield h
52 yield! primesSieve <| Seq.filter (fun m -> m % h <> 0) sequence
53 }
54 let primes = primesSieve <| (Seq.initInfinite id |> Seq.skip 2)
55 printfn "first primes: %A" <| (Seq.take 100 primes |> Seq.toList)
56
57 [<EntryPoint>]
58 let main argv =
59 question1 ()
60 question4 ()
61 0
62