Skip to content

Commit

Permalink
feat: add native Array
Browse files Browse the repository at this point in the history
  • Loading branch information
SrijanSriv committed Jan 7, 2023
1 parent 6458394 commit af2ba3d
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 3 deletions.
13 changes: 13 additions & 0 deletions com/welambdas/lambda/Interpreter.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ public Object call(Interpreter interpreter, List<Object> arguments) {
@Override
public String toString() { return "<native fn>"; }
});
globals.define("Array", new LambdaCallable() {
@Override
public int arity() {
return 1;
}

@Override
public Object call(Interpreter interpreter,
List<Object> arguments) {
int size = (int)(double)arguments.get(0);
return new LambdaArray(size);
}
});
}

@Override
Expand Down
68 changes: 68 additions & 0 deletions com/welambdas/lambda/LambdaArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.welambdas.lambda;

import java.util.List;

class LambdaArray extends LambdaInstance {
private final Object[] elements;

LambdaArray(int size) {
super(null);
elements = new Object[size];
}

@Override
Object get(Token name) {
if (name.lexeme.equals("get")) {
return new LambdaCallable() {
@Override
public int arity() {
return 1;
}

@Override
public Object call(Interpreter interpreter,
List<Object> arguments) {
int index = (int)(double)arguments.get(0);
return elements[index];
}
};
} else if (name.lexeme.equals("set")) {
return new LambdaCallable() {
@Override
public int arity() {
return 2;
}

@Override
public Object call(Interpreter interpreter,
List<Object> arguments) {
int index = (int)(double)arguments.get(0);
Object value = arguments.get(1);
return elements[index] = value;
}
};
} else if (name.lexeme.equals("length")) {
return (double) elements.length;
}

throw new RuntimeError(name,
"Undefined property '" + name.lexeme + "'.");
}

@Override
void set(Token name, Object value) {
throw new RuntimeError(name, "Can't add properties to arrays.");
}

@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
for (int i = 0; i < elements.length; i++) {
if (i != 0) buffer.append(", ");
buffer.append(elements[i]);
}
buffer.append("]");
return buffer.toString();
}
}
6 changes: 3 additions & 3 deletions hello.orz
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#>test
var arr = Array(3);

var greeting = Greeter("srijan", "evening");
arr.set(1, "word");

greeting.greet();
print arr.get(1);
6 changes: 6 additions & 0 deletions lib/maps.orz
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class Maps {
init (modulo_val) {
this.modulo_val = modulo_val;
}
insert(number)
}

0 comments on commit af2ba3d

Please sign in to comment.