Синтаксический сахар (= вместо return) для коротких функций

This commit is contained in:
Victor 2015-07-28 21:17:16 +03:00
parent 951d6c97bd
commit 08847a59f1
2 changed files with 18 additions and 8 deletions

View File

@ -64,18 +64,18 @@ print "\n\n"
array = newarray(2, 2, 2, 2) array = newarray(2, 2, 2, 2)
print array print array
add = def(a,b) return a+b add = def(a,b) = a+b
sub = def(a,b) return a-b sub = def(a,b) = a-b
mul = def(a,b) return a*b mul = def(a,b) = a*b
div = def(a,b) return a/b div = def(a,b) = a/b
cube = def(x) return x*mul(x, x) cube = def(x) = x*mul(x, x)
print "\n\n" print "\n\n"
print mul(8, 5) print mul(8, 5)
print "\n" print "\n"
print cube(2) print cube(2)
functions = [add, sub, mul, div] functions = [add, sub, mul, div]
def function(f, a, b) return f(a, b) def function(f, a, b) = f(a, b)
for i = 0, i < 4, i = i + 1 { for i = 0, i < 4, i = i + 1 {
print "\n" print "\n"
print functions[i] print functions[i]

View File

@ -141,6 +141,10 @@ public final class Parser {
argNames.add(consume(TokenType.WORD).getText()); argNames.add(consume(TokenType.WORD).getText());
match(TokenType.COMMA); match(TokenType.COMMA);
} }
if (lookMatch(0, TokenType.EQ)) {
match(TokenType.EQ);
return new FunctionDefineStatement(name, argNames, new ReturnStatement(expression()));
}
final Statement body = statementOrBlock(); final Statement body = statementOrBlock();
return new FunctionDefineStatement(name, argNames, body); return new FunctionDefineStatement(name, argNames, body);
} }
@ -411,8 +415,14 @@ public final class Parser {
argNames.add(consume(TokenType.WORD).getText()); argNames.add(consume(TokenType.WORD).getText());
match(TokenType.COMMA); match(TokenType.COMMA);
} }
final Statement body = statementOrBlock(); Statement statement;
return new ValueExpression(new UserDefinedFunction(argNames, body)); if (lookMatch(0, TokenType.EQ)) {
match(TokenType.EQ);
statement = new ReturnStatement(expression());
} else {
statement = statementOrBlock();
}
return new ValueExpression(new UserDefinedFunction(argNames, statement));
} }
if (match(TokenType.LPAREN)) { if (match(TokenType.LPAREN)) {
Expression result = expression(); Expression result = expression();