-
Notifications
You must be signed in to change notification settings - Fork 0
Modules, Functions and Classes
-
array<char>
is used instead ofstring
- To comment, you use
#
instead of//
- A
main()
function needs to be defined - To make a new class instance, you need to use the
new
keyword. An example is:michael = new person("Michael", 17)
- You do not have to type
;
at the end of each line
REMINDER: Indentation and letter casing matters in NHP
To create modules, you use the mod
keyword.
To import modules, you do include "directory/file_name.nhp"
To call functions contained in modules, you do module_name::func()
To create classes in NHP, you would do the following:
class example_class:
Annotating type properties is still needed
Classes are for the most part like Python classes. As a result, you still need def __init__
when initiating attributes for an class instance.
To create functions in NHP, you would do the following:
def func_name() type:
The type
keyword defines return type. If you want a value to be return, define type
. Else, the function will return nothing.
Parameters require you specify the type that will be used by the parameter.
Example: def test_func(int numberToTakeIn) int:
Example 1: Uses both modules and functions. This example demonstrates the calculation of the Fibonacci Sequence and of a factorial by using two functions nested in a module called "recursion".
include "io.nhp"
mod recursion:
def fib(int n) int:
return 1 if n <= 1 else fib(n - 1) + fib(n - 2)
def fact(int n) int:
return 1 if n == 0 else n * fact(n - 1)
def main():
#io::print(recursion::fib(35))
io::print(recursion::fact(0-1))
Example 2: Uses modules, classes, and functions.
mod myproject:
class person:
array<char> name
int age
def __init__(array<char> name, int age):
self.name = name
self.age = age
def myClosure() int:
return self.age
def main():
michael = new person("Michael", 17)
class list<T>:
array<T> buffer
def __init__(int size, T default):
self.buffer = new T[size](default)
def fib(int n) int:
return (n <= 1) if 1 else fib(n - 1) + fib(n - 2)
def main():
myproject::main()
myList = new myproject::list<int>(10, 5)