Last active
January 24, 2017 12:02
-
-
Save OnurGumus/80abbfde4f494c785ea741890c3e7e63 to your computer and use it in GitHub Desktop.
Fsharp Workshop 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System | |
module Async = | |
let map f workflow = async { let! res = workflow | |
return f res } | |
let bind f workflow = async.Bind(workflow, f) | |
let readInput() = async { return Console.ReadLine() } | |
let random() = async { return System.Random().Next(100) } | |
// | |
let write (out : string) = async { return Console.WriteLine(out) } | |
type ComparisonResult = | |
| Equal of int | |
| Great of int | |
| Small of int | |
let parseInput s = | |
Int32.TryParse s |> function | |
| false, _ -> Result.Error s | |
| true, i -> Result.Ok i | |
let test (target : int) (input : int) = | |
if input > target then Great input | |
else if input < target then Small input | |
else Equal input | |
let (|GreaterThan|_|) smallerNumber n = | |
if n > smallerNumber then Some n | |
else None | |
let (|DivisibleBy|_|) dividedBy n = | |
if n % dividedBy = 0 then Some n | |
else None | |
let testSmaller = | |
function | |
| Great(DivisibleBy 5 n) -> Small n | |
| other -> other | |
let testDivisibleBy = | |
function | |
| Small(GreaterThan 50 n) -> Great n | |
| other -> other | |
let asyncResultMap k = | |
k | |
|> Result.map | |
|> Async.map | |
type ContOrStop = | |
| Continue | |
| Stop | |
let handle comparison = | |
async { | |
match comparison with | |
| Error _ -> | |
do! write "Re enter the number" | |
return Continue | |
| Ok(Equal _) -> | |
do! write "bingo!" | |
return Stop | |
| Ok(Great _) -> | |
do! write "Greater" | |
return Continue | |
| Ok(Small _) -> | |
do! write "Smaller" | |
return Continue | |
} | |
let rec turn r = | |
readInput | |
>> Async.map parseInput | |
>> asyncResultMap (test r) | |
>> asyncResultMap testSmaller | |
>> asyncResultMap testDivisibleBy | |
>> Async.bind handle | |
>> Async.bind (function | |
| Continue -> turn r | |
| Stop -> async.Return()) | |
<| () | |
[<EntryPoint>] | |
let main argv = | |
Async.bind random | |
>> Async.bind turn | |
>> Async.RunSynchronously | |
<| (write "Enter a number:") | |
0 // return an integer exit code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment