Skip to content

Instantly share code, notes, and snippets.

@kayceesrk
Created April 1, 2015 17:38
Show Gist options
  • Save kayceesrk/afd704bc172be9553988 to your computer and use it in GitHub Desktop.
Save kayceesrk/afd704bc172be9553988 to your computer and use it in GitHub Desktop.
MLton serialization example
fun serialize1 () =
let
val v = "ABCD"
val ser_v = MLton.serialize v
val v' = MLton.deserialize ser_v
in
print (v' ^ "\n")
end
datatype List = Nil | Cons of (int * List)
fun serialize2 () =
let
fun listToStringRest Nil = "]"
| listToStringRest (Cons (x, xs)) = ","^(Int.toString x)^(listToStringRest xs)
fun listToString Nil = "[]"
| listToString (Cons (x,xs)) = "["^(Int.toString x)^(listToStringRest xs)
val l = Cons (1, Cons (2, Cons (3, Nil)))
val ser_l = MLton.serialize l
val l' = MLton.deserialize ser_l
in
print (listToString l'^"\n")
end
fun serialize3 () =
let
val r = ref 1
val ser_r = MLton.serialize r
val _ = r := 2
val r' : int ref = MLton.deserialize ser_r
(* r' is still 1 since serialize copies mutable objects at the point of
* serialization *)
in
print (Int.toString (!r')^"\n")
end
fun serialize4 () =
let
(* Functions can also be serialized. *)
val f = fn x => x+1
val ser_f = MLton.serialize f
val f' : (int -> int) = MLton.deserialize ser_f
in
print (Int.toString (f' 1)^"\n")
end
fun serialize5 () =
let
(* library functions can also be serialized. *)
val f = fn s => print (s^"\n")
val ser_f = MLton.serialize f
val f' : string -> unit = MLton.deserialize ser_f
in
f' (Int.toString 0)
end
val () = (serialize5 o serialize4 o serialize3 o serialize2 o serialize1) ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment