Skip to content

Instantly share code, notes, and snippets.

@kolektiv
Created January 8, 2016 17:23
Show Gist options
  • Save kolektiv/2ce763dcbb5726af47b5 to your computer and use it in GitHub Desktop.
Save kolektiv/2ce763dcbb5726af47b5 to your computer and use it in GitHub Desktop.
Overloading monadic operators?
// Implementations
module Reader =
let bind (f: 'e -> 't, binder: 't -> 'e -> 'u) : 'e -> 'u =
fun e ->
binder (f e) e
// Specializations
type Bind =
| Bind with
static member (>>=) (Bind, m: 'e -> 't) =
fun (f: 't -> 'e -> 'u) ->
Reader.bind (m, f)
static member (>>=) (Bind, m: Async<'t>) =
fun (f: 't -> Async<'u>) ->
async.Bind (m, f)
// Generalizations
module Monad =
let inline bind m f =
(Bind >>= m) f
// Operators
let inline (>>=) m f =
Monad.bind m f
// Test
[<EntryPoint>]
let main _ =
// Async
let asyncm = async.Return 9
let asyncf = fun i -> async.Return (i % 2 = 0)
let asyncx = (asyncm >>= asyncf) |> Async.RunSynchronously
// Reader
let readerm = fun e -> List.head e
let readerf = fun i e -> (i + List.sum e) = 5
let readerx = (readerm >>= readerf) [ 2; 3 ]
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment