Skip to content

Instantly share code, notes, and snippets.

@shwars
Created April 24, 2014 21:54
Show Gist options
  • Save shwars/11270852 to your computer and use it in GitHub Desktop.
Save shwars/11270852 to your computer and use it in GitHub Desktop.
Монада Maybe и мотивирующий пример с вводом-выводом
open System
let read() =
printf ">"
let s = Console.ReadLine()
try
Some((int)s)
with
_ -> None
let a = read()
if a<>None then
let b = read()
if b<>None then printfn "Result is %d" (a.Value+b.Value)
else printfn "Bad input"
else printfn "Bad input"
let bind a f =
if a=None then None
else f (a.Value)
bind (read()) (fun x -> bind (read()) (fun y -> Some(x+y)))
let (>>=) a f =
if a=None then None
else f (a.Value)
read() >>= (fun x -> read() >>= (fun y->Some(x+y)))
// Monadic Syntax
let read() =
printf ">"
let s = Console.ReadLine()
try
Some((int)s)
with
_ -> None
let (>>=) a f =
if a=None then None
else f (a.Value)
read() >>= (fun x -> read() >>= (fun y->Some(x+y)))
type MaybeBuilder () =
member b.Bind(a,f) = a>>=f
member b.Return(x) = Some(x)
member b.Zero() = None
member b.Combine(x,y) = x>>=(fun _ -> y)
let maybe = new MaybeBuilder()
maybe {
let! x = read()
let! y = read()
return x+y
}
maybe {
let! x = read()
let! y = read()
let z = 2
printfn "x=%d, y=%d, z=%d" x y z
return (x+y)*z
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment