Skip to content

Instantly share code, notes, and snippets.

@kfl
Last active December 17, 2015 07:09
Show Gist options
  • Save kfl/5570950 to your computer and use it in GitHub Desktop.
Save kfl/5570950 to your computer and use it in GitHub Desktop.
Dynamic types via exceptions or references in SML
structure Dyn :> Dyn =
struct
type t = unit -> unit
fun new () =
let val r = ref NONE
in { into = fn x => fn () => r := SOME x,
out = fn f => (f(); !r before r := NONE)}
end
end
(* Implementation of `before`:
infix bef
fun x bef y = x
*)
signature Dyn =
sig
type t
val new : unit -> {into : 'a -> t, out : t -> 'a option }
end
structure Dyn :> Dyn =
struct
type t = exn
fun new () =
let exception Dyn of 'a
in { into = fn x => Dyn x,
out = fn Dyn x => SOME x
| _ => NONE }
end
end
(*
app use ["Dyn.sig", "Dyn-ref.sml", "Dyntest.sml"];
app use ["Dyn.sig", "Dyn.sml", "Dyntest.sml"];
*)
val int = Dyn.new()
val str = Dyn.new()
val bool = Dyn.new()
val ds = [#into int 42, #into str "fourty two", #into int 23, #into bool true]
val ints = List.mapPartial (#out int) ds
@kfl
Copy link
Author

kfl commented Jun 18, 2013

The into label should have been named from but I'll leave it as-is for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment