Skip to content

Instantly share code, notes, and snippets.

@leon737
Last active December 20, 2015 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leon737/6056653 to your computer and use it in GitHub Desktop.
Save leon737/6056653 to your computer and use it in GitHub Desktop.
F# monads
Monads implemented:
Maybe
Reader
Writer
type Maybe<'a> =
| Just of 'a
| Nothing
let Return x = Just x
let Bind mx f =
match mx with
| Just x -> f x
| Nothing -> Nothing
let (>>=) = Bind
type Reader<'v> = Reader of 'v
let Return v = Reader v
let runReader mx d =
match mx with
| Reader v -> v d
let Bind mx f =
match mx with
| Reader v -> Reader (fun z -> (v z) |> f |> runReader <| z)
let (>>=) = Bind
/////////////////////////////////////////////////////////////////////////////
let greeter =
Return (fun n -> "hello, " + n + "!")
let calc (s:string) =
Return (fun (n:string) -> s.Length - n.Length)
let config = "leon"
let r = runReader (greeter >>= calc) config
type Writer<'d, 'v> = Writer of 'd * 'v
let Tell d f = f d
let Return v = fun d -> Writer(d,v)
let Join d mx =
match mx with
| Writer(x:string,v) -> Writer(d+x, v)
let Bind mx f =
match mx with
| Writer(d,v) -> f v |> Join d
let runWriter mx =
match mx with
| Writer(d,v) -> d,v
let (>>=) = Bind
/////////////////////////////////////////////////////////////////////////////
let half x =
Tell ( sprintf "I just halved %d ! " x ) <| Return ( x / 2 )
let log, result = half 8 >>= half |> runWriter
printfn "Log: %s" log
printfn "Result: %d" result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment