Created
June 30, 2021 16:51
-
-
Save BashkaMen/a1eebf106a4bb24db51268c516ff20f2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
let inline (|HasMap|) f x = (^x : (static member Map : ('a -> 'b) * ^x -> ^z) f, x) // define type class | |
let inline map f (HasMap f x) = x // call type class instance | |
let inline (|HasPure|) x = (^x : (static member Pure : 'a -> ^x)x) | |
let inline pure' (HasPure x) = x | |
let inline (|HasBind|) f x = (^x : (static member Bind : ('a -> ^z) * ^x -> ^z)f, x) | |
let inline bind f (HasBind f x) = x | |
type Either<'l, 'r> = | |
| Left of 'l | |
| Right of 'r with | |
static member Pure x = Right x | |
static member Bind(f, x) = | |
match x with | |
| Right r -> f r | |
| Left l -> Left l | |
static member Map(f, x) = | |
match x with | |
| Right r -> Either.Pure (f r) | |
| Left l -> Left l | |
let parseInt (input: string) = | |
match Int32.TryParse(input) with | |
| true, x -> Right x | |
| false, _ -> Left "invalid input" | |
let divide a b = | |
if b <> 0 then Right (a / b) | |
else (Left "divide by zero") | |
let run = | |
parseInt "100" | |
|> map (fun x -> x + 10) | |
|> bind (fun x -> divide x 2) // right 55 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment