visitMappingExpr method
Implementation
@override
Object? visitMappingExpr(Expr.Mapping expr) {
Stmt.Functional mp;
var func = evaluate(expr.lambda);
if (func is! LoxFunction) {
throw RuntimeError(
expr.name, "Only func can be used as Mapping function");
} else {
mp = func.declaration;
}
Object? objects = evaluate(expr.callee);
LoxFunction iterableFun = LoxFunction(mp, environment, false);
switch (expr.name.lexeme) {
case 'map':
if (objects is! Iterable) {
throw RuntimeError(expr.name, "Only iterable can map function");
}
return objects.map((i) {
return iterableFun.call(this, [i], {});
}).toList();
case 'where':
if (objects is! Iterable) {
throw RuntimeError(expr.name, "Only iterable can use where function");
}
return objects.where((i) {
return iterableFun.call(this, [i], {}) == true;
}).toList();
case 'sort':
if (objects is! List) {
throw RuntimeError(expr.name, "Only List can be sorted");
}
objects.sort((a, b) {
return iterableFun.call(this, [a, b], {}) as int;
});
return null;
case 'forEach':
if (objects is! Iterable) {
throw RuntimeError(
expr.name, "Only iterable can use forEach function");
}
for (var i in objects) {
iterableFun.call(this, [i], {});
}
return null;
}
throw RuntimeError(expr.name, "Only Array have mapping.");
}