How do I instantiate a functor in SML?

If I have the following functor, how can I instantiate using ListMapFn

?

functor G(M: ORD_MAP where type Key.ord_key = string) :

      

+3


source to share


2 answers


Something like

structure S = G(ListMapFn(type ord_key = string; val compare = String.compare))

      



or, if you prefer to name the instance ListMap

:

structure ListMap = ListMapFn(type ord_key = string; val compare = String.compare)
structure S = G(ListMap)

      

+4


source


To explain a little about the syntax of functors, here are some examples.

Some preliminary announcements first, so we have something to work with.

signature FOO =
sig
  val foo : unit -> unit
end


structure FooUnit : FOO =
struct
  fun foo () = ()
end


structure FooPrint : FOO =
struct
  fun foo () = print "Foo\n"
end

      

Now. when we create functors that only take one structure as an argument, this is optional unless we write functor FooFn (f : FOO)

or functor FooFn (structure f : FOO)

. In fact, this only applies when the functor takes one structure as an argument:

(* Optionally to write "structure f : FOO" as there is only one argument *)
functor FooFn (f : FOO) = struct
  val foo = f.foo
end

      

However, when the functor takes two or more arguments, the keyword structure must be used. Note that the functor can take other arguments, such as an integer value.

(* Note there is no delimiter, just a space and the structure keyword *)
functor FooFooFn (structure f1 : FOO
                  structure f2 : FOO) =
struct
  val foo1 = f1.foo
  val foo2 = f2.foo
end

      

We also have several options when applying the functor and returning the resulting structure. The first is straight.

structure f1 = FooFn (FooUnit)

      



However, it is a bit "special case", as we define it, "inlined", omitting struct

and end

part

structure f2 = FooFn (fun foo () = print "Inlined\n")

      

or we can be a little more detailed and include part struct

and end

. However, both of these functions only work because the functor takes one argument

structure f2_1 = FooFn (struct fun foo () = print "Inlined\n" end)

      

The syntax is somewhat the same when the functor takes multiple arguments

(* Again note there is no delimiter, so we can have it on the same line *)
structure f3 = FooFooFn (structure f1 = FooUnit structure f2 = FooPrint)

      

it somewhat resembles records, since the order does not matter

(* And we can even switch the order *)
structure f4 = FooFooFn (structure f2 = FooUnit
                         structure f1 = FooPrint)

      

+5


source







All Articles