Can I use pa_monad to provide an η extension?

I am developing a library where several state monads are usually mixed. What state is being mixed is not known a priori, but is likely to be determined at the application level. Therefore, my solution is to develop one state monad, which has an expandable hidden state.

(** ObjectStateMonad for composable State Monads *)
module ObjectStateMonad =
  struct
    (* A state monad yields tuple of a state-object and an observable value *)
    type ('a, 'b) monad = 'a -> ('a * 'b)

    (* usual bind, just more type parameters *)
    let bind : (('a, 'b) monad) -> ('b -> ('a, 'c) monad) -> ('a, 'c) monad = 
      fun m -> 
      fun f ->
      fun s ->
        let (st, obs) = m(s) in
        ( (f obs) st)

    (* run, as usual *)
    let run m a = m(a)

    type ('a, 'b) field = { field_get : 'a -> 'b ; field_set : 'a -> 'b -> 'a }

    (* get does not directly expose the state but requires a "getter" *)
    let get f = 
      let m : 'a -> ('a * 'b) = fun s -> (s, f.field_get s)
      in m

    (* put requires a "setter" function to modify the state *)
    let put f = 
      fun b ->
      let m : 'a -> ('a * unit) = fun s -> 
    let s2 : 'a = (f.field_set s b) in (s2, ()) 
      in m

    let yield a = fun s -> (s, a)

    let return = yield

    let rec repeat m = function
      | 0 -> m
      | n -> bind m (fun _ -> repeat m (n - 1))       

  end

My implementation uses string polymorphism to achieve extensibility:

module FooState = struct
  open ObjectStateMonad

  type state_t = int

  class state_container = object
    val _foo : state_t = 0
    method get_foo = _foo
    method set_foo n = {< _foo = n >} 
  end

  let field = { field_get = (fun a -> (a#get_foo : state_t)) ; field_set = fun a b -> a#set_foo b }

  (* just an example operation *)
  let increment s = ( 
    perform n <-- get field ; 
    _ <-- put field (n+1); 
    return n 
  ) s

end

The module above demonstrates how the plug-in ability works: create a class that inherits from all the corresponding state containers, create an instance of this class and perform operations on them.

, - OCaml ( ), ( s increment). , pa_monad, , ?

: pa_monad η- ?

.

+4
1

pa_monad; s , perform. ,

open ObjectStateMonad
open FooState

let state, result =
  (perform
    _ <-- increment;
    _ <-- increment;
    a <-- increment;
    return a) (new state_container)
in
print_int state#get_foo ; print_char ':' ; print_int result

3:2, .

, s . N- :

let increment = 
  perform n <-- get field ; 
  _ <-- put field (n+1); 
  return n

.

0

Source: https://habr.com/ru/post/1540375/


All Articles