Last active
December 17, 2015 07:09
-
-
Save kfl/5570950 to your computer and use it in GitHub Desktop.
Dynamic types via exceptions or references in SML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
*) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
signature Dyn = | |
sig | |
type t | |
val new : unit -> {into : 'a -> t, out : t -> 'a option } | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
into
label should have been namedfrom
but I'll leave it as-is for now.