Skip to content

Instantly share code, notes, and snippets.

@timo
Created October 26, 2014 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timo/19bca00c702507cabad3 to your computer and use it in GitHub Desktop.
Save timo/19bca00c702507cabad3 to your computer and use it in GitHub Desktop.
gives "zeroed target id in work pass" - probably because of the "once { next }", which is what i added last.
my $ADD = 0;
my $SUBSTRACT = 1;
my $MULTIPLY = 2;
my $DEVIDE = 3;
my $SUM = 4;
my %functions = (
$ADD => sub (@args) {
return @args[0] + @args[1];
},
$SUBSTRACT => sub (@args) {
return @args[0] - @args[1];
},
$MULTIPLY => sub (@args) {
return @args[0] * @args[1];
},
$DEVIDE => sub (@args) {
return @args[0].Num / @args[1];
},
$SUM => sub (@args) {
my $sum = 0;
for @args -> $arg {
$sum += $arg;
}
return $sum;
}
);
sub evaluate_ast(@ast) {
my $oper = @ast[0];
my $func = %functions{$oper};
my @evaluated_args;
for @ast -> $piece {
once { next }
if $piece ~~ Array {
@evaluated_args.push: evaluate_ast $piece;
} else {
@evaluated_args.push: $piece;
}
}
return $func(@evaluated_args);
}
sub timeAST(@ast) {
my $t0 = time;
my $sum = 0;
my $iterations = 100_000;
for (1..$iterations) {
$sum += evaluate_ast(@ast);
}
my $compute_time = time - $t0;
say "COMPUTED [$iterations] ITERATIONS IN [$compute_time] SECONDS";
if (abs($sum - 3900000) > 0.001 ) {
die "WRONG SUM $sum";
}
}
my $ast = [$SUM,
[$SUBSTRACT,[$ADD,[$DEVIDE,[$MULTIPLY,10,20],30],40],50],
[$SUBSTRACT,[$ADD,[$DEVIDE,[$MULTIPLY,20,30],40],50],60],
[$SUBSTRACT,[$ADD,[$DEVIDE,[$MULTIPLY,30,40],50],60],70],
[$SUBSTRACT,[$ADD,[$DEVIDE,[$MULTIPLY,40,50],60],70],80]
];
timeAST($ast);
@smls
Copy link

smls commented Oct 26, 2014

In evaluate_ast, why are you using for + push + temporary array instead of:

@ast.map({ ... }).$func

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment