Skip to content

Instantly share code, notes, and snippets.

@lindig
Created October 7, 2016 08:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lindig/d4be3b6642cbb187cbee14753b517ca4 to your computer and use it in GitHub Desktop.
Save lindig/d4be3b6642cbb187cbee14753b517ca4 to your computer and use it in GitHub Desktop.
OCaml Functors - small examples
==> func0.ml <==
module Debug = struct
let debug msg = Printf.eprintf "debug: %s\n" msg
let error msg = Printf.eprintf "error: %s\n" msg
end
let main () =
let argv = Array.to_list Sys.argv in
let args = List.tl argv in
( List.iter print_endline args
; Debug.debug "all done"
; exit 0
)
let () = if !Sys.interactive then () else main ()
==> func1.ml <==
module Debug = struct
let debug prg msg = Printf.eprintf "%s debug: %s\n" prg msg
let error prg msg = Printf.eprintf "%s error: %s\n" prg msg
end
let main () =
let argv = Array.to_list Sys.argv in
let this = List.hd argv in
let args = List.tl argv in
( List.iter print_endline args
; Debug.debug this "all done"
; exit 0
)
let () = if !Sys.interactive then () else main ()
==> func2.ml <==
module type PRG = sig
val name: string
end
module Debug (Prg : PRG) = struct
let debug msg = Printf.eprintf "%s debug: %s\n" Prg.name msg
let error msg = Printf.eprintf "%s error: %s\n" Prg.name msg
end
module X = struct
let name = "hello"
end
module D = Debug(X)
module D' = Debug(struct let name = "hello" end)
let main () =
let argv = Array.to_list Sys.argv in
let args = List.tl argv in
( List.iter print_endline args
; D.debug "all done"
; exit 0
)
let () = if !Sys.interactive then () else main ()
==> func3.ml <==
module type ELEMENT = sig
type t
val compare: t -> t -> int
end
module MySet (Element: ELEMENT ) = struct
type set = Element.t list
let add x set = x::set
let mem x set = List.exists (fun y -> Element.compare x y = 0) set
end
(* /usr/lib/ocaml/string.mli:
type t = string
(** An alias for the type of strings. *)
val compare: t -> t -> int
(** The comparison function for strings, with the same specification as
{!Pervasives.compare}. Along with the type [t], this function [compare]
allows the module [String] to be passed as argument to the functors
{!Set.Make} and {!Map.Make}. *)
*)
module StringSet = MySet(String)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment