Search code examples
ocamlfunctor

How to reference an argument that is a functor


I'm defining a module using the below header:

module MakePuzzleSolver
         (MakeCollection
            : functor (Element : sig type t end) ->
                      (Collections.COLLECTION with type elt = Element.t))
         (Puzzle : PUZZLEDESCRIPTION)
       : (PUZZLESOLVER with type state = Puzzle.state
                        and type move = Puzzle.move) =

This is the first time I've ever tried using a functor as an argument, and I'm a little confused about how/whether I can include references within the MakePuzzleSolver module to functions that are included in the functor's signature. E.g., the functor's signature includes a function called "add" that I'd like to reference, but of course when I try MakeCollection.add I get a "functor cannot have components" error message. Do I need to create an implementation of the functor within MakePuzzleSolver to be able to reference it?


Solution

  • You need to apply the functor. Much like with a function (and this is what it is underneath the hood), you need to apply a function to its argument in order to use its result.

    In your example, it looks like that you're missing the final piece of the puzzle - you need an extra argument that will denote the element of your collection, e.g.,

    module MakePuzzleSolver
             (MakeCollection
                : functor (Element : sig type t end) ->
                          (Collections.COLLECTION with type elt = Element.t))
             (Puzzle : PUZZLEDESCRIPTION)
             (Element : sig type t end) (* the missing element *)
           : (PUZZLESOLVER with type state = Puzzle.state
                            and type move = Puzzle.move) = struct
      module Collection = MakeCollection(Element)
      (* now you can use Collection.add *)
      ...
    
    end