Chapter 9 • Module system
Modules in SomonScript
Modules let us split code into small files and reuse it. This is especially important for large projects.
1. A module with one function
Every .som file is a module. In this example, the file math.som exports a function with содир, and the file main.som imports it with ворид. Both files are in the same folder.
Math module
Exporting (содир) and importing (ворид) a function from a module.
example.som
// file: math.som
содир функсия ҷамъ(а: рақам, б: рақам): рақам {
бозгашт а + б;
}
// file: main.som
ворид { ҷамъ } аз "./math";
тағ натиҷа: рақам = ҷамъ(2, 3);
чоп.сабт("Натиҷа: " + натиҷа);terminal
somon run main.som
Натиҷа: 52. A module with several exports
A module can export several functions or classes. We can import them together.
Library module
Exporting several functions from one module.
example.som
// file: library.som
содир функсия илова_китоб(ном: сатр): беджавоб {
чоп.сабт("Китоб илова шуд: " + ном);
}
содир функсия нест_кардан(ном: сатр): беджавоб {
чоп.сабт("Китоб нест карда шуд: " + ном);
}
// file: main.som
ворид { илова_китоб, нест_кардан } аз "./library";
илова_китоб("SomonScript барои мактабҳо");
нест_кардан("SomonScript барои мактабҳо");terminal
somon run main.som
Китоб илова шуд: SomonScript барои мактабҳо
Китоб нест карда шуд: SomonScript барои мактабҳо3. Exercises
These exercises help students understand how modules work.
- Create a module math2 that exports multiplication and division functions, and use them in another file.
- Create a module that stores a list of books and has functions for adding, removing and displaying the list.
- Create a module auth that exports functions for checking a login and password.