If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Saturday, October 19, 2013

Callbacks using mutable references (ML)

val cbs: (int -> unit) list ref = ref []
(*
x = ref 4 means x has a reference to a value of type int with initial value 4
x := 5 means update the value x refers to with value 5
val y = (!x) means store the value x refers to in y
*)
fun onKeyEvent f = cbs := f :: (!cbs)
fun onEvent i =
let fun loop fs =
case fs of
[] => ()
|f::fs' => (f i; loop fs')
in loop (!cbs) end
(* some client code *)
val timesPressed = ref 0
val _ = onKeyEvent (fn _ => timesPressed := (!timesPressed) + 1
fun printIfPressed i =
onKeyEvent (fn j =>
if i=j
then print ("you pressed " ^ Int.ToString i)
else ()
view raw gistfile1.sml hosted with ❤ by GitHub

No comments:

Post a Comment