简体   繁体   中英

What's the difference between include, require and open in OCaml?

For example,

include: include Ppx_core

open: open Core.Std

require: #require "compiler-libs.common"

and use: #use "topfind"

  • include re-exports the components of the module in the current structure: the module you are in will contain all definitions that are in Ppx_core .
  • open makes the components of the module directly accessible in the typing environment. Instead of typing Core.Std.element you can just type element .
  • #require is a Topfind command that finds a library and loads it, making its modules accessible to you.
  • #use behave as ifcopying a full file directly into your toplevel.

Note that the # -keywords are not part of the OCaml language but are toplevel commands: they won't work if you try to compile your file.

The include Module.Name statement in the module definition will include all definitions from a module named Module.Name . The definitions will be included roughly as they were copy-pasted. If the include Module.Name occurs inside of the module type definition (aka signature definition), the the Module.Name should be a valid (known to a compiler) module type. It will include the definition of a module type as it is (without including any type sharing constraints).

The open Module.Name statement occurring in both module implementation and module signature, will allow you to refer to definitions (values, types, submodules) of a Module.Name without using a fully qualified named, ie, using short names without the Module.Name prefix.

The #require statement is not a statement at all and is not a part of OCaml grammar. It is special directive of the OCaml toplevel - the interactive loop. The same as ipython has its own directives. The require directive will load the specified package, and all its dependencies. Moreover, this directive is not a part of a standard OCaml toplevel distribution, but is added by the topfind script that is a part of the ocamlfind toolkit. The #use directive is used to load and evaluate a script. For example #use "topfind" will load and evaluate the topfind script from the OCaml standard library folder. This script will register the require directive. There are also #load and #load_rec directives, that work on a more fine-granular level, rather than packages -- these directives are intendend to load libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM