Sanchime.Learn/Monads/ReaderMonad.fs

26 lines
817 B
Forth
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

namespace Sanchime.Monads
[<AutoOpen>]
module Reader =
// 读取器单子是计算状态并产生一个值't的单子
type Reader<'s, 't> = Reader of ('s -> 't)
// 单位元不读取任何操作因此产生Reader<unit, 'a>
let unit v = Reader (fun () -> v)
// 绑定操作接受Reader和一个读取状态另一部分的函数'a -> Reader<'b, 'c>
// 并在一个元组中产生一个读取两个状态值的Reader<('d * 'b), 'c>
let bind f (Reader (g)) = Reader (fun (a, b) ->
let v = g a in
let (Reader h) = f v in
h b)
type ReaderBuilder () =
member __.Return(v) = unit v
member __.Bind(v, f) = bind f v
member __.Delay(f) = Reader (fun s ->
let (Reader h) = f ()
h s)
let reader = ReaderBuilder ()