Question

Using functors in OCaml is essentially running code during compile-time (in that way I think they are closer to C++ templates then to Java generics).

Thus my question is: does the compiler perform any optimizations before compiling them, or does it start generating code straight away or does it try to perform any optimizations beforehand?

The question is more practical that it might seem. Quite often I use Map.Make or a similar functor to generate map/hashtable/etc for a given type. When I use it in multiple modules, I start to get worried, because I think that the compiler will start to do the same thing multiple times (and the compilation speed starts to become an issue for me, especially coming from the scripting language background). So do I need to get worried? Or if I perform Map.Make(MyModule) in multiple modules would compiler be able to say "ohai I've just compiled this functor with this type I probably don't need to do it again?"

Yes I know that I can have a separate utils module and run all the functors in there, but I generally try to avoid utils-like-kitchen-sink modules.

Était-ce utile?

La solution

would compiler be able to say "ohai I've just compiled this functor with this type I probably don't need to do it again?"

You are thinking of the way templates are typically compiled by C++ compilers. The compilation scheme of ocamlc and ocamlopt instead produces generic code that does not need to be duplicated.

The OCaml functor Map.Make is compiled only once for all modules it may be applied to. The same code is executed when you call iter from Map.Make(String) and iter from Map.Make(Float). Or indeed when you run iter from two different applications of Map.Make to String.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top