Linear types in OCaml -


rust has linear type system. there (good) way simulate in ocaml? e.g., when using ocaml-lua, want make sure functions called when lua in specific state (table on top of stack, etc).

as suggested john rivers, can use monadic style represent "effectful" computation in way hides linear constraint in effect api. below 1 example type ('a, 'st) t used represent computation using file handle (whose identity implicit/unspoken guarantee cannot duplicated), product result of type 'a , leave file handle in state 'st (a phantom type being either "open" or "close"). have use run of monad¹ anything, , type ensure file handles correctly closed after use.

module file : sig   type ('a, 'st) t   type open_st = open   type close_st = close    val bind : ('a, 's1) t -> ('a -> ('b, 's2) t) -> ('b, 's2) t    val open_ : string -> (unit, open_st) t   val read : (string, open_st) t   val close : (unit, close_st) t    val run : ('a, close_st) t -> 'a end = struct   type ('a, 'st) t = unit -> 'a   type open_st = open   type close_st = close    let run m = m ()    let bind m f = fun () ->     let x = run m in     run (f x)    let close = fun () ->     print_endline "[lib] close"    let read = fun () ->     let result = "toto" in     print_endline ("[lib] read " ^ result);     result    let open_ path = fun () ->      print_endline ("[lib] open " ^ path) end      let test =   let open file in   let (>>=) = bind in   run begin     open_ "/tmp/foo" >>= fun () ->     read >>= fun content ->     print_endline ("[user] read " ^ content);     close   end 

of course, meant give taste of style of api. more serious uses, see oleg's monadic regions examples.

you may interested in research programming language mezzo, aims variant of ml finer-grained control of state (and related effectful patterns) through linear typing discipline separated resources. note research experiment now, not aimed @ users. ats relevant, though less ml-like. rust may reasonable "practical" counterpart these experiments.

¹: not monad because has no return/unit combinator, point force type-controlled sequencing monadic bind operator does. have map, though.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -