Imports and ExportsEdit on GitHub
Larger projects are best maintained when the project’s code is broken up into small files. Imports are used to access values within other modules and exports are used to control which values within a module are available to other modules.
When we want to make a value in a module available for another module to import, we export it. The easiest way to export values from a module is to export everything:
In this example, the values
five could both be imported into another module.
Grain also includes a way to exclude values from being exported this way.
Here, the only value available for export is
It sometimes makes sense to export everything from a module, but often it’s best to explicitly declare which values should be exported.
Using the same example, we could choose to only export
add with an export statement.
We could also define the export inline:
Exports work the same way for data types. If we had a record type that we wanted to include in another module, we’d just export it as we’d export anything else.
If we export a variant type, each variant constructor gets exported and is available to other modules. For example, in this code:
Bus will all be imported with the
Things can be imported from standard libraries or other files we’ve written.
We can import a module by giving it a name and providing the path to the module.
The name in quotes,
'lists', is the path to the module. Grain knows how to find all of the modules in the standard library, so we can just say
lists without having to determine where the standard library files exist on our computer.
We can import values from files we’ve written by providing the path to that file. We don’t need to include the
With these two files in the same directory,
main.gr, we’d have the workings of a full program.
As you’ve seen so far, we can import an entire module from the standard library by giving it a name beginning with a capital letter, like so:
Module names don’t have to mirror the path name. We can name them whatever we’d like:
If we want to include all of the values from another module in our program, we can use an asterisk.
Individual values in a module can be imported by placing the names in curly braces.