Skip to content
/ monkey Public

Monkey programming language interpreters in Rust and Go

Notifications You must be signed in to change notification settings

VPagani/monkey

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

47 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Monkey Programming Language

A dynamic toy programming language implemented twice from scratch in Rust (./src/monkey-rs) and Go (./src/monkey-go) based on the book Writing an Interpreter in Go by Thorsten Ball

Examples

Hello World

puts("hello world");
//> hello world

Variables and Expressions

let a = 1;
puts(a + 1);
//> 2

let b = 6;
puts(a + b);
//> 8

let b = " foo";
puts(4 + a + b);
//> 15 foo

Data types

let str = "this is a string";
puts(len(str));
//> 16

let arr = ["this", "is", "an", "array", 1, true];
puts(len(arr));
//> 6

let hsh = { "this": "is", "a": "hash", true: false, 1: 101 };
puts(hsh["this"] + hsh["a"])
//> ishash

Functions

let factorial = fn(n) {
  if (n <= 1) {
    return 1;
  }

  return n * factorial(n - 1);
}

puts(factorial(8));
//> 40320

let fibonacci = fn(n) {
  if (n <= 1) {
    return 1;
  }

  return fibonacci(n - 2) + fibonacci(n -1);
}

puts(fibonacci(25))
//> 121393

Built-in Functions

let arr = [0, 1, 2, 3, 5, 6, 7, 8, 9]

puts(len(arr))
//> 10

puts(first(arr))
//> 0

puts(last(arr))
//> 9

puts(rest(arr))
//> [1, 2, 3, 5, 6, 7, 8, 9]

puts(push(arr, 10))
//> [0, 1, 2, 3, 5, 6, 7, 8, 9, 10]

Macro Expressions

quote(expression):

Returns expression as a raw AST object without evaluating (except for expressions inside unquote)

unquote(expression):

Can only be used inside quote argument

Evaluate expression or quoted AST object passed as argument

puts(quote(foobar + barfoo));
//> QUOTE((foobar + barfoo))

puts(quote(8 + unquote(4 + 4)));
//> QUOTE((8 + 8))

let quotedInfixExpression = quote(4 + 4);
puts(quote(unquote(4 + 4) + unquote(quotedInfixExpression)));
//> QUOTE((8 + (4 + 4)))

Macro Functions

let unless = macro(condition, consequence, alternative) {
  quote(if (!unquote(condition)) {
    unquote(consequence);
  } else {
    unquote(alternative);
  });
};

unless(10 > 5, puts("not greater"), puts("greater"));
//> greater

About

Monkey programming language interpreters in Rust and Go

Resources

Stars

Watchers

Forks