Assignment 7
[Scala.git] / Assignment_07-FSharp / Assignment_07-FSharp / Program.fs
diff --git a/Assignment_07-FSharp/Assignment_07-FSharp/Program.fs b/Assignment_07-FSharp/Assignment_07-FSharp/Program.fs
new file mode 100644 (file)
index 0000000..601ecdb
--- /dev/null
@@ -0,0 +1,62 @@
+open System
+
+// Question 1.
+type Stack<'a> = 
+    | Elem of 'a * Stack<'a>
+    | Empty
+    member this.Push a = Elem (a, this)
+    member this.Top = 
+        match this with
+        | Elem (a, _) -> a
+        | Empty -> failwith "Empty stack!"
+    member this.Pop = 
+        match this with
+        | Elem (_, rest) -> rest
+        | Empty -> failwith "Empty stack!"
+    override this.ToString () =
+        match this with
+        | Elem (e, rest) -> e.ToString() + "," + rest.ToString()
+        | Empty -> "Empty"
+
+type Foo () = class end
+type Bar () = inherit Foo ()
+
+let question1 () = 
+    printfn "Question 1"
+    let a = (((Empty.Push "hello").Push "world").Push "it's fun").Pop
+    printfn "a: %O" a
+    assert (a.ToString () = "world,hello,Empty")
+
+    let b = ((Empty.Push 1).Push 3)
+    printfn "b.Top: %O" b.Top
+    assert (b.Top = 3)
+
+    let c : Stack<Bar> = (Empty.Push <| Bar ()).Push <| Bar ()
+    printfn "%A" <|
+        match c.Top with
+        | :? Bar -> true
+        | _ -> false
+
+    let d : Stack<#Foo> = (Empty.Push <| Bar ()).Push <| Bar ()
+    printfn "%A" <|
+        match d.Top with
+        | :? Bar -> true
+        | _ -> false
+
+// Question 4.
+let question4 () =
+    let rec primesSieve sequence =
+        seq {
+            let h = Seq.head sequence
+            yield h
+            yield! primesSieve <| Seq.filter (fun m -> m % h <> 0) sequence
+        }
+    let primes = primesSieve <| (Seq.initInfinite id |> Seq.skip 2)
+    printfn "first primes: %A" <| (Seq.take 100 primes |> Seq.toList)
+
+[<EntryPoint>]
+let main argv = 
+    question1 ()
+    question4 ()
+    0
+