Skip to content

Instantly share code, notes, and snippets.

@CaglarGonul
Last active December 15, 2015 17:19
Show Gist options
  • Save CaglarGonul/5295619 to your computer and use it in GitHub Desktop.
Save CaglarGonul/5295619 to your computer and use it in GitHub Desktop.
A callback implementation in ML.
(*We need a mutable list to store the list of registered callbacks.*)
(*The initial list will be empty.*)
val cbs : (int -> unit) list ref = ref []
(*We need a public function to register the callbacks on the the callback list*)
fun registerCallBack f =
cbs := f::(!cbs)
(*When a specific action occurs we will call this function.*)
(*This function will call each call back with a parameter.*)
(*So we can see if any call back will respond to this specific paramater.*)
(*In this case this specific parameter will be named as i*)
fun onAction i =
let fun loop fs =
case fs of
[] => ()
| f::fs' => (f i ; loop fs')
in
loop (!cbs)
end
(*Let's register some callbacks*)
val _ = registerCallBack (fn x => if x=4 then print ("you pressed "^Int.toString 4 ^ "\n") else ())
val _ = registerCallBack (fn x => if x=6 then print ("you pressed "^Int.toString 6 ^ "\n") else ())
val _ = registerCallBack (fn x => if x=4 then print ("you pressed "^Int.toString 4 ^ "\n") else ())
val _ = registerCallBack (fn x => if x=8 then print ("you pressed "^Int.toString 8 ^ "\n") else ())
Standard ML of New Jersey v110.74 [built: Wed May 2 05:23:34 2012]
- use "mycb.sml";
[opening mycb.sml]
[autoloading]
[library $SMLNJ-BASIS/basis.cm is stable]
[autoloading done]
val cbs = ref [fn,fn,fn,fn] : (int -> unit) list ref
val registerCallBack = fn : (int -> unit) -> unit
val onAction = fn : int -> unit
val it = () : unit
- onAction 4;
you pressed 4
you pressed 4
val it = () : unit
-
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment