Interp - an Interpreted Programming Language Pt.15 - Demo Functions

1 minute read

It’s Pt. 15 and today we look at some real world examples. Thank you for sticking with me through this series :). This will be the last part for now.

Functions

Hello, world!

Let’s start simple!

Hello.it:

Print("Hello, world!")
$ interp Hello.it
Hello, world!

ForEach

ForEach takes a list and a function and calls the function with every item in the list.

ForEach.it:

fun ForEach(list, function) {
    var i = 0
    while list[i] != void {
        function(list[i])
        i += 1
    }
}
$ interp
> imp "ForEach.it"
> ForEach([1,2,3], Print)
1
2
3
<void>

Slice

Slice a list.

Slice.it:

fun Slice(list, start, end) {
    var new_list = []
    var i = start
    while i < end {
        new_list &= [list[i]]
        i += 1
    }
    ret new_list
}
$ interp
> imp "Slice.it"
> slice([1,2,3,4], 1, 3)
[2, 3]

Object

In this one we create an object (or dictionary) and call some methods with it. ref means that the argument is passed by reference, and not by value.

Object.it:

fun PersonBirthday(person) {
    person.age += 1
}

fun PersonCanDrink(person) {
    ret person.age >= 18
}
$ interp
> imp "Object.it"
> var john = { first_name="John", last_name="Smith", age=17 }
> john.age
17
> PersonCanDrink(john)
false
> PersonBirthday(ref john)
> john.age
18
> PersonCanDrink(john)
true

Sqrt

Calculate the square root of a number.

Sqrt.it:

fun Sqrt(n) {
    ret Float(n) ^ 0.5
}
$ interp
> imp "Sqrt.it"
> Sqrt(2)
1.4142135623730951

Fib

Recursive Fibonacci.

Fib.it:

fun Fib(n) {
    if n <= 2 {
        ret 1
    }
    ret Fib(n-1) + Fib(n-2)
}
$ interp
> imp "Fib.it"
> Fib(10)
55

Cat

Let’s implement the unix cat command.

Cat.it:

var i = 2
while clargs[i] != void {
    Output(ReadFile(clargs[i]))
    i += 1
}
if i == 2 {
    while true {
        var line = Input()
        if line == null {
            brk
        }
        Print(line)
    }
}

Eval

How to execute aribtrary code in a string. Works only in *nix due to the tmp directory.

Eval.it:

var code = Input()
WriteFile("/tmp/it_eval.it", code)
imp "/tmp/it_eval.it"
$ interp Eval.it
Print(1)
1

Source Code

Source code for this part can be found here.

Next Up

Execute Interp online at the Webshell.

Click here for all parts.

Updated: