Skip to content

Commit

Permalink
featre [op]: Added a=>f and a/f
Browse files Browse the repository at this point in the history
Each operator performs:
 - `a => f`  map `f` over `a`
 - `a / f`   reduce `a` over `
  • Loading branch information
vihanb committed Oct 2, 2016
1 parent cb916f8 commit b1a45cd
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 5 deletions.
42 changes: 41 additions & 1 deletion src/interpreter/core/env/func.es6
Expand Up @@ -269,11 +269,51 @@ export default class CheddarFunction extends CheddarClass {
}]
]);

RHS_Operator = new Map([...CheddarClass.Operator,
RHS_Operator = new Map([...CheddarClass.RHS_Operator,
['&', (self, value) => {
// Copy args to new function
let new_args = self.args.slice(1);
return new self.constructor(new_args, (a,b, args) => self.exec([value, ...args], null));
}],

['/', (LHS, RHS) => {
let res;

try {
return RHS.value.reduce(function(item1, item2) {
res = LHS.exec([ item1, item2 ], null);

if (typeof res === 'string')
throw res;

return res;
});
} catch (e) {
return e;
}
}],

['=>', (LHS, RHS) => {
let CheddarArray = require("../primitives/Array");

if (RHS.constructor.Name !== "Array")
return CheddarError.NO_OP_BEHAVIOR;

RHS = RHS.value;
let res;
let out = HelperInit(CheddarArray);

for (var i = 0; i < RHS.length; i++) {
res = LHS.exec([ RHS[i] ]);

if (typeof res === 'string') {
return res;
} else {
out.value.push(res || new NIL);
}
}

return out;
}]
])

Expand Down
17 changes: 14 additions & 3 deletions src/stdlib/primitive/Array/lib/reduce.es6
Expand Up @@ -8,8 +8,19 @@ export default (api) => ["reduce", api.var(new api.func(
let self = input("self");
let callback = input("callback");

return self.value.reduce(function(item1, item2, index, array) {
return input("callback").exec([item1, item2, api.init(api.number, 10, 0, index), self], null);
});
let res;

try {
return self.value.reduce(function(item1, item2, index, array) {
res = input("callback").exec([item1, item2, api.init(api.number, 10, 0, index), self], null);

if (typeof res === 'string')
throw res;

return res;
});
} catch (e) {
return e;
}
}
))];
4 changes: 3 additions & 1 deletion src/tokenizer/consts/ops.es6
Expand Up @@ -35,7 +35,8 @@ export const OP = [
'@"', 'has',
'log', 'sign',
'root',
'is', 'actually'
'is', 'actually',
'=>'
].sort((a, b) => b.length - a.length);

// Unary operators
Expand Down Expand Up @@ -91,6 +92,7 @@ export const PRECEDENCE = new Map([
['is', 14000],
['actually', 14000],
['root', 14000],
['=>', 13000],
['*', 13000],
['/', 13000],
['%', 13000],
Expand Down

0 comments on commit b1a45cd

Please sign in to comment.