Skip to content

Instantly share code, notes, and snippets.

let (>=>) f g
= fun x -> (f x) >>= g;;
let Join mm
= mm >>= fun x -> x;;
@SteveGilham
SteveGilham / gist:eff2610b17077bafd38b
Created April 26, 2015 14:04
List of monads to monad of lists
let rec Sequence l
= match l with
| [] -> Return []
| h::t -> h >>= fun h1 -> (Sequence t) >>= fun t1 -> Return (h1::t1);;
@SteveGilham
SteveGilham / gist:4b84d12c9db342eb0a3b
Created April 26, 2015 14:03
List monad operations
let ReturnList x = [x]
let FailList = []
let (>>=*) m f = List.concat (List.map f m);;
@SteveGilham
SteveGilham / gist:29e08bc2eea7acfadd74
Created April 26, 2015 14:03
Option monad operations
let ReturnOption x = Some x
let FailOption = None
let (>>=?) m f = Option.bind f m;;
@SteveGilham
SteveGilham / gist:737d12bdbb1046e18b40
Created April 26, 2015 14:02
I/O monad definition
type 'a io = IO of (unit -> 'a)
exception IOFailure
let RunIO (IO f) = f();;
@SteveGilham
SteveGilham / gist:4acbf564c4a7f1f7118d
Created April 26, 2015 14:01
I/O monad operations
let ReturnIO x = IO (fun () -> x)
let FailIO = IO (fun () -> raise IOFailure)
let (>>=) m f = IO (fun () -> RunIO(f(RunIO m)));;
@SteveGilham
SteveGilham / gist:b1cb2dc37df4a9267bf7
Created April 26, 2015 14:00
Monadic character I/O
let GetC = IO (fun () -> System.Console.ReadKey(true).KeyChar)
let PutC (c:char) = IO (fun () -> System.Console.Write c) ;;
let EchoC = GetC >>= PutC;;
@SteveGilham
SteveGilham / gist:4900c10576204213f400
Created April 26, 2015 13:59
Monadic string reader
let GetS length =
let rec get chars count =
if count > 0
then GetC >>= fun c -> get (chars@[c]) (count – 1)
else Return IO String(List.toArray chars)
get [] length;;