So far we have used the functionality which is available by default every time we start a new Nim file. This can be extended with modules, which give more functionality for some specific topic.
Some of the most used Nim modules are:
-
strutils
: additional functionality when dealing with strings -
sequtils
: additional functionality for sequences -
math
: mathematical functions (logarithms, square roots, …), trigonometry (sin, cos, …) -
times
: measure and deal with time
But there are many more, both in what’s called the standard library and in the nimble package manager.
If we want to import a module and all of its functionality, all we have to do is put import <moduleName>
in our file.
This is commonly done on the top so we can easily see what our code uses.
link:{source-dir}/stringutils.nim[role=include]
-
Importing strutils.
-
Using
split
fromstrutils
module. It splits the string in a sequence of words. -
toUpperAscii
converts all ASCII letters to uppercase. -
repeat
is also fromstrutils
module, and it repeats either a character or a whole string the requested amount of times.
@["My", "string", "with", "whitespace."]
MY STRING WITH WHITESPACE.
!!!!!
link:{source-dir}/maths.nim[role=include]
-
Importing math.
-
Converting degrees to radians with
degToRad
. -
sin
takes radians. We round (also frommath
module) the result to at most 2 decimal places. (Otherwise the result would be: 0.4999999999999999) -
Math module also has
^
operator for calculating powers of a number.
0.5235987755982988
0.5
32
Often times we have so much code in a project that it makes sense to split it into pieces that each does a certain thing.
If you create two files side by side in a folder, let’s call them firstFile.nim
and secondFile.nim
, you can import one from the other as a module:
proc plus*(a, b: int): int = (1)
return a + b
proc minus(a, b: int): int = (2)
return a - b
-
Notice how the
plus
procedure now has an asterisk (*
) after it’s name, this tells Nim that another file importing this one will be able to use this procedure. -
By contrast this will not be visible when importing this file.
import firstFile (1)
echo plus(5, 10) (2)
echo minus(10, 5) # error (3)
-
Here we import
firstFile.nim
. We don’t need to put the.nim
extension on here. -
This will work fine and output
15
as it’s declared infirstFile
and visible to us. -
However this will throw an error as the
minus
procedure is not visible since it doesn’t have an asterisk behind it’s name.
In case you have more than these two files, you might want to organize them in a subdirectory (or more than one subdirectory). With the following directory structure:
.
├── myOtherSubdir
│ ├── fifthFile.nim
│ └── fourthFile.nim
├── mySubdir
│ └── thirdFile.nim
├── firstFile.nim
└── secondFile.nim
if you wanted to import all other files in your secondFile.nim
this is how you would do it:
import firstFile
import mySubdir/thirdFile
import myOtherSubdir / [fourthFile, fifthFile]