Skip to content

Instantly share code, notes, and snippets.

@superherointj
Created June 18, 2020 18:15
Show Gist options
  • Save superherointj/836887570c0c3e3caf7bc0b0febd00ea to your computer and use it in GitHub Desktop.
Save superherointj/836887570c0c3e3caf7bc0b0febd00ea to your computer and use it in GitHub Desktop.
OCaml Functor Demo1
(* Functor example *)
module type Dog = sig
val barks : bool
end;;
module type Animal = sig (* Shouldn't `Animal` module/functor have some parameter in it's signature??? *)
val approach : unit -> string
end;;
module ADog : Dog = struct
let barks = true
end;;
module AnAnimal (D: Dog): Animal = struct (* I've set a `sort of parameter` here... but never defined it in types. Is it expected to work this way? *)
let approach () =
match D.barks with
| true -> "BARKS!"
| false -> "is silent."
;;
end;;
module Hanna = AnAnimal(ADog);;
let () = print_endline ("Hanna " ^ (Hanna.approach ()))
@superherointj
Copy link
Author

@Octachron Today at 5:28 PM

The module type Animal is the module type of the result.
You need to name the module parameter in order to use it. You can define the functor type, but this is more verbose for little gain

module type f = functor(X:sig val x: int end) -> sig val y : int end
module F: f = functor (X:sig val x:int end) -> struct let y = X.x + 1 end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment