Created
January 8, 2016 17:23
-
-
Save kolektiv/2ce763dcbb5726af47b5 to your computer and use it in GitHub Desktop.
Overloading monadic operators?
This file contains 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
// 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