Basic Syntax - Liby99/menhera GitHub Wiki

Here we demonstrate some syntax of Menhera Language:

Let expression

let a = 3 in
a + 5

We define a variable a to be integer 3 and continue the calculation in the expression a + 5. The result will be 8. Here we have omitted the type declaration of a which is a int. If we want to declare the type explicitly, we can do

let a: int = 3 in
a + 5

This is exactly the same as the previous demo.

Functions

Let's take a look at what a function could look like:

(a) => a + 3

In the example above we defined an anonymous function that takes in an int and return that integer incremented by 3. Again this is typed using type inference, so if we want to fully explicitly type the expression, we need to write

(a: int): int => a + 3

We are going to span this topic a little more by talking about how do we call a function

let f = (a) => a + 3 in
f(5)

Here we defined a function f which is exactly the function we demonstrated before, and we call that function with integer 5.

If you are wondering how do we explicitly define the type of the above expression:

let f: (int) -> int = (a: int): int => a + 3 in
f(5)

Of course we can define a function with slightly more arguments:

let sum = (a, b) => a + b in
sum(3, 5)

Here sum takes 2 integers and return a single integer. The type of sum will be (int, int) -> int.

Further more, all of these functions are closures, and functions are first-class. That means we can have function that returns a function:

let sum = (a) => (b) => a + b in
sum(3)(5)

Now we've changed the definition of sum to curry-style. Which means that sum now takes in a single integer, and returns a function closure, that takes in another integer, add them together, and return the result sum.

If we explicitly type these functions, the expression will become

let sum: (int) -> (int) -> int = 
    (a: int): (int) -> int => 
        (b: int): int => 
            a + b 
in
sum(3)(5)

Although a little bit verbose, we can get the idea of how do we define higher-order functions.