Skip to content

Instantly share code, notes, and snippets.

@marcoonroad
Last active May 15, 2017 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcoonroad/7144cdeb07b0c30f1b7458a07e33f7cd to your computer and use it in GitHub Desktop.
Save marcoonroad/7144cdeb07b0c30f1b7458a07e33f7cd to your computer and use it in GitHub Desktop.
Encoding Ownership types in OCaml...

We can indeed see a let-expression as it were a sole contextual with-expression known in some languages, e.g, Python. So, there is a translation on syntax-level for:

let X = M
N

as:

with M as X:
  N

With that general idea in mind, we can apply some sort of ownership on let-expressions if the target language supports:

  • Abstract types, either through Existential types or Rank-N polymorphism
  • HM-like type inference

To be sound, such languages will perform an escape analysis checking if some lexically introduced abstract type would escape its definition scope. Said that, we can pass such abstract type as it were a ghost type, for example, or even deliver a concrete type as an abstract one. The point is to the value to carry this locally introduced type information, together with that, type systems will disallow such value from escaping the abstract type definition's scope (surely, we must disable implicit substituitions such unification, this is the why of encoding the value as an "abstract one").

module Ownership ( ) : sig
type owner
type ('owner, 'value) owned = private 'value
val acquire : 'value -> (owner, 'value) owned
val release : (owner, 'value) owned -> 'value
end = struct
type owner = unit
type ('owner, 'value) owned = 'value
let acquire value = value
let release value = value
end;;
utop # #use "Ownership.ml";;
module Ownership :
functor () ->
sig
type owner
type ('owner, 'value) owned = private 'value
val acquire : 'value -> (owner, 'value) owned
val release : (owner, 'value) owned -> 'value
end
utop # let module A = Ownership ( ) in
let x = A.acquire 5 in
x;;
Error: This expression has type (A.owner, int) A.owned
but an expression was expected of type (A.owner, int) A.owned
The type constructor A.owned would escape its scope
utop # let module A = Ownership ( ) in
let x = A.acquire 5 in
A.release x;;
- : int = 5
utop #
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment