Created
April 1, 2013 00:12
-
-
Save phpfiddle/5282555 to your computer and use it in GitHub Desktop.
PHP Simple AST example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function evaluate($env, $expr) { | |
list($e, $v) = each($expr); | |
switch(strtolower($e)) { | |
case "add": | |
return evaluate($env, array_slice($v,0, 1)) + evaluate($env, array_slice($v, 1, 1)); | |
break; | |
case "multiply": | |
return evaluate($env, array_slice($v,0, 1)) * evaluate($env, array_slice($v, 1, 1)); | |
break; | |
case "variable": | |
return $env[$v]; | |
break; | |
case "number": | |
return $v; | |
break; | |
} | |
} | |
$environment = array("a" => 3, "b" => 4, "c" => 7); | |
$expression_tree = array( | |
"add" => array( | |
"variable" => "a", | |
"multiply" => array( | |
"number" => 2, | |
"variable" => "b" | |
) | |
) | |
); | |
echo evaluate($environment, $expression_tree); | |
function number($n) { | |
return function($env) use ($n) { | |
return $n; | |
}; | |
} | |
function variable($a) { | |
return function($env) use ($a) { | |
return $env[$a]; | |
}; | |
} | |
function add($a, $b) { | |
return function($env) use ($a, $b) { | |
return $a($env) + $b($env); | |
}; | |
} | |
function mul($a, $b) { | |
return function($env) use ($a, $b) { | |
return $a($env) * $b($env); | |
}; | |
} | |
function evaluate2($tree, $env) { | |
return $tree($env); | |
} | |
$tree = add(variable("a"), mul(number(2), variable("b"))); | |
echo evaluate2($tree, $environment); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment