Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment

View file

@ -0,0 +1,17 @@
Given a program in the language (as a string or AST) with a free variable named <var>x</var> (or another name if that is not valid syntax), evaluate it with <var>x</var> bound to a provided value, then evaluate it again with <var>x</var> bound to another provided value, then subtract the result of the first from the second and return or print it.
Do so in a way which:
* does not involve string manipulation of the input source code
* is plausibly extensible to a runtime-chosen set of bindings rather than just <var>x</var>
* does not make <var>x</var> a ''global'' variable
or note that these are impossible.
;See also:
* For more general examples and language-specific details, see [[Eval]].
* [[Dynamic variable names]] is a similar task.
<br><br>

View file

@ -0,0 +1,3 @@
PROC eval_with_x = (STRING code, INT a, b)STRING:
(INT x=a; evaluate(code) ) + (INT x=b; evaluate(code));
print((eval_with_x("2 ** x", 3, 5), new line))

View file

@ -0,0 +1,6 @@
on task_with_x(pgrm, x1, x2)
local rslt1, rslt2
set rslt1 to run script pgrm with parameters {x1}
set rslt2 to run script pgrm with parameters {x2}
rslt2 - rslt1
end task_with_x

View file

@ -0,0 +1,6 @@
set pgrm_with_x to "
on run {x}
2^x
end"
task_with_x(pgrm_with_x, 3, 5)

View file

@ -0,0 +1,8 @@
code: [x * 2]
fn: function [x]->
do with 'x code
a: fn 2
b: fn 4
print b - a

View file

@ -0,0 +1,32 @@
msgbox % first := evalWithX("x + 4", 5)
msgbox % second := evalWithX("x + 4", 6)
msgbox % second - first
return
evalWithX(expression, xvalue)
{
global script
script =
(
expression(){
x = %xvalue% ; := would need quotes
return %expression%
}
)
renameFunction("expression", "") ; remove any previous expressions
gosub load ; cannot use addScript inside a function yet
exp := "expression"
return %exp%()
}
load:
DllCall(A_AhkPath "\addScript","Str",script,"Uchar",0,"Cdecl UInt")
return
renameFunction(funcName, newname){
static
x%newname% := newname ; store newname in a static variable so its memory is not freed
strput(newname, &x%newname%, strlen(newname) + 1)
if fnp := FindFunc(funcName)
numput(&x%newname%, fnp+0, 0, "uint")
}

View file

@ -0,0 +1,8 @@
expression$ = "x^2 - 7"
one = FN_eval_with_x(expression$, 1.2)
two = FN_eval_with_x(expression$, 3.4)
PRINT two - one
END
DEF FN_eval_with_x(expr$, x)
= EVAL(expr$)

View file

@ -0,0 +1,9 @@
( ( eval-with-x
= code a b argument
. !arg:((=?code),?a,?b,?argument)
& (!b:?x&!code$!argument)
+ -1*(!a:?x&!code$!argument)
)
& out$(eval-with-x$((='(.$x^!arg)),3,5,2))
& out$(eval-with-x$((='(.$x^!arg)),12,13,2))
);

View file

@ -0,0 +1,5 @@
(def ^:dynamic x nil)
(defn eval-with-x [program a b]
(- (binding [x b] (eval program))
(binding [x a] (eval program))))

View file

@ -0,0 +1,2 @@
(eval-with-x '(* x x) 4 9)
=> 65

View file

@ -0,0 +1,3 @@
(defn eval-with-x [program a b]
(let [func (eval `(fn [~'x] ~program))]
(- (func b) (func a))))

View file

@ -0,0 +1,2 @@
(eval-with-x '(* x x) 4 9)
=> 65

View file

@ -0,0 +1,4 @@
(defun eval-with-x (program a b)
(let ((at-a (eval `(let ((x ',a)) ,program)))
(at-b (eval `(let ((x ',b)) ,program))))
(- at-b at-a)))

View file

@ -0,0 +1,2 @@
(eval-with-x '(exp x) 0 1)
=> 1.7182817

View file

@ -0,0 +1,5 @@
(defun eval-with-x (program a b)
(let* ((f (compile nil `(lambda (x) ,program)))
(at-a (funcall f a))
(at-b (funcall f b)))
(- at-b at-a)))

View file

@ -0,0 +1,15 @@
# Constructing an environment has to be done by way of evaluation
#for historical reasons which will hopefully be entirely eliminated soon.
def bindX(value) {
def [resolver, env] := e` # bind x and capture its resolver and the
def x # resulting environment
`.evalToPair(safeScope)
resolver.resolve(value) # set the value
return env
}
def evalWithX(program, a, b) {
def atA := program.eval(bindX(a))
def atB := program.eval(bindX(b))
return atB - atA
}

View file

@ -0,0 +1,2 @@
? evalWithX(e`(x :float64).exp()`, 0, 1)
# value: 1.7182818284590455

View file

@ -0,0 +1,12 @@
(define (eval-with-x prog x)
(eval prog (environment-new (list (list 'x x)))))
(define prog '( + 1 (* x x)))
(eval-with-x prog 10) → 101
(eval-with-x prog 1000) → 1000001
(- (eval-with-x prog 1000) (eval-with-x prog 10)) → 999900
;; check x is unbound (no global)
x
😖️ error: #|user| : unbound variable : x

View file

@ -0,0 +1,12 @@
import extensions;
import extensions'scripting;
public program()
{
var text := program_arguments[1];
var arg := program_arguments[2];
var program := lscript.interpret(text);
console.printLine(
text,",",arg," = ",program.eval(arg.toReal()));
}

View file

@ -0,0 +1,21 @@
-module( runtime_evaluation ).
-export( [evaluate_form/2, form_from_string/1, task/0] ).
evaluate_form( Form, {Variable_name, Value} ) ->
Bindings = erl_eval:add_binding( Variable_name, Value, erl_eval:new_bindings() ),
{value, Evaluation, _} = erl_eval:expr( Form, Bindings ),
Evaluation.
form_from_string( String ) ->
{ok, Tokens, _} = erl_scan:string( String ),
{ok, [Form]} = erl_parse:parse_exprs( Tokens ),
Form.
task() ->
Form = form_from_string( "X." ),
Variable1 = evaluate_form( Form, {'X', 1} ),
io:fwrite( "~p~n", [Variable1] ),
Variable2 = evaluate_form( Form, {'X', 2} ),
io:fwrite( "~p~n", [Variable2] ),
io:fwrite( "~p~n", [Variable2 - Variable1] ).

View file

@ -0,0 +1,3 @@
USE: eval
: eval-bi@- ( a b program -- n )
tuck [ ( y -- z ) eval ] 2bi@ - ;

View file

@ -0,0 +1,2 @@
IN: scratchpad 9 4 "dup *" eval-bi@- .
65

View file

@ -0,0 +1 @@
: bi@- ( a b quot -- n ) bi@ - ; inline

View file

@ -0,0 +1,2 @@
IN: scratchpad 9 4 [ dup * ] bi@- .
65

View file

@ -0,0 +1,4 @@
SYMBOL: x
: eval-with-x ( a b program -- n )
tuck
[ [ x ] dip [ ( -- y ) eval ] curry with-variable ] 2bi@ - ;

View file

@ -0,0 +1,4 @@
IN: scratchpad 9 4 "x get dup *" eval-with-x .
65
IN: scratchpad x get .
f

View file

@ -0,0 +1,7 @@
: f-" ( a b snippet" -- )
[char] " parse ( code len )
2dup 2>r evaluate
swap 2r> evaluate
- . ;
2 3 f-" dup *" \ 5 (3*3 - 2*2)

View file

@ -0,0 +1,15 @@
: :macro ( "name <char> ccc<char>" -- )
: [CHAR] ; PARSE POSTPONE SLITERAL POSTPONE EVALUATE
POSTPONE ; IMMEDIATE
;
:macro times 0 do ;
: test 8 times ." spam " loop ;
see test
: test
8 0
DO .\" spam "
LOOP
; ok

View file

@ -0,0 +1,7 @@
defmacro add100() (+ x 100)
var x 23
var firstresult (add100)
x = 1000
print
+ firstresult (add100)

View file

@ -0,0 +1,8 @@
def add100() (+ .x 100)
(dict) # create an environment capable of holding dynamic bindings
var .x 23 # create a binding in the dictionary
var firstresult (add100)
.x = 1000
print
+ firstresult (add100)

View file

@ -0,0 +1,4 @@
(dict)
var .x 23
(dict)
print .x # fails

View file

@ -0,0 +1,67 @@
package main
import (
"bitbucket.org/binet/go-eval/pkg/eval"
"fmt"
"go/parser"
"go/token"
)
func main() {
// an expression on x
squareExpr := "x*x"
// parse to abstract syntax tree
fset := token.NewFileSet()
squareAst, err := parser.ParseExpr(squareExpr)
if err != nil {
fmt.Println(err)
return
}
// create an environment or "world"
w := eval.NewWorld()
// allocate a variable
wVar := new(intV)
// bind the variable to the name x
err = w.DefineVar("x", eval.IntType, wVar)
if err != nil {
fmt.Println(err)
return
}
// bind the expression AST to the world
squareCode, err := w.CompileExpr(fset, squareAst)
if err != nil {
fmt.Println(err)
return
}
// directly manipulate value of variable within world
*wVar = 5
// evaluate
r0, err := squareCode.Run()
if err != nil {
fmt.Println(err)
return
}
// change value
*wVar--
// revaluate
r1, err := squareCode.Run()
if err != nil {
fmt.Println(err)
return
}
// print difference
fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))
}
// int value implementation.
type intV int64
func (v *intV) String() string { return fmt.Sprint(*v) }
func (v *intV) Get(*eval.Thread) int64 { return int64(*v) }
func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }
func (v *intV) Assign(t *eval.Thread, o eval.Value) {
*v = intV(o.(eval.IntValue).Get(t))
}

View file

@ -0,0 +1,3 @@
def cruncher = { x1, x2, program ->
Eval.x(x1, program) - Eval.x(x2, program)
}

View file

@ -0,0 +1,5 @@
def fibonacciProgram = '''
x < 1 ? 0 : x == 1 ? 1 : (2..x).inject([0,1]){i, j -> [i[1], i[0]+i[1]]}[1]
'''
println "F(${10}) - F(${5}) = ${Eval.x(10, fibonacciProgram)} - ${Eval.x(5, fibonacciProgram)} = " + cruncher(10, 5, fibonacciProgram)

View file

@ -0,0 +1,7 @@
EvalWithX=. monad : 0
'CODE V0 V1'=. y
(". CODE [ x=. V1) - (". CODE [ x=. V0)
)
EvalWithX '^x';0;1
1.71828183

View file

@ -0,0 +1,2 @@
(0&({::) -~&>/@:(128!:2&.>) 1 2&{) '^';0;1
1.71828183

View file

@ -0,0 +1,3 @@
EvalDiffWithY=: dyad define
-~/verb def x"_1 y
)

View file

@ -0,0 +1,2 @@
'^y' EvalDiffWithY 0 1
1.71828

View file

@ -0,0 +1,4 @@
EvalDiffWithName=: adverb define
:
-~/m adverb def ('(m)=.y';x)"_1 y
)

View file

@ -0,0 +1,4 @@
'^George' 'George' EvalDiffWithName 0 1
1.71828
'Z + 2^Z' 'Z' EvalDiffWithName 2 3
5

View file

@ -0,0 +1,68 @@
import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class Eval {
private static final String CLASS_NAME = "TempPleaseDeleteMe";
private static class StringCompiler
extends SimpleJavaFileObject {
final String m_sourceCode;
private StringCompiler( final String sourceCode ) {
super( URI.create( "string:///" + CLASS_NAME + Kind.SOURCE.extension ), Kind.SOURCE );
m_sourceCode = sourceCode;
}
@Override
public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {
return m_sourceCode;
}
private boolean compile() {
final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
return javac.getTask( null, javac.getStandardFileManager( null, null, null ),
null, null, null, Arrays.asList( this )
).call();
}
private double callEval( final double x )
throws Exception {
final Class<?> clarse = Class.forName( CLASS_NAME );
final Method eval = clarse.getMethod( "eval", double.class );
return ( Double ) eval.invoke( null, x );
}
}
public static double evalWithX( final String code, final double x )
throws Exception {
final StringCompiler sc = new StringCompiler(
"class "
+ CLASS_NAME
+ "{public static double eval(double x){return ("
+ code
+ ");}}"
);
if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" );
return sc.callEval( x );
}
public static void main( final String [] args )
throws Exception /* lazy programmer */ {
final String expression = args [ 0 ];
final double x1 = Double.parseDouble( args [ 1 ] );
final double x2 = Double.parseDouble( args [ 2 ] );
System.out.println(
evalWithX( expression, x1 )
- evalWithX( expression, x2 )
);
}
}

View file

@ -0,0 +1,7 @@
function evalWithX(expr, a, b) {
var x = a;
var atA = eval(expr);
x = b;
var atB = eval(expr);
return atB - atA;
}

View file

@ -0,0 +1 @@
evalWithX('Math.exp(x)', 0, 1) // returns 1.718281828459045

View file

@ -0,0 +1,18 @@
/* Runtime evaluation in an environment, in Jsish */
function evalWithX(expr, a, b) {
var x = a;
var atA = eval(expr);
x = b;
var atB = eval(expr);
return atB - atA;
}
;evalWithX('Math.exp(x)', 0, 1);
;evalWithX('Math.exp(x)', 1, 0);
/*
=!EXPECTSTART!=
evalWithX('Math.exp(x)', 0, 1) ==> 1.71828182845905
evalWithX('Math.exp(x)', 1, 0) ==> -1.71828182845905
=!EXPECTEND!=
*/

View file

@ -0,0 +1,10 @@
macro evalwithx(expr, a, b)
return quote
x = $a
tmp = $expr
x = $b
return $expr - tmp
end
end
@evalwithx(2 ^ x, 3, 5) # raw expression (AST)

View file

@ -0,0 +1,9 @@
function evalwithx(expr::Expr, a, b)
a = eval(quote let x = $a; return $expr end end)
b = eval(quote let x = $b; return $expr end end)
return b - a
end
evalwithx(expr::AbstractString, a, b) = evalwithx(parse(expr), a, b)
evalwithx(:(2 ^ x), 3, 5)
evalwithx("2 ^ x", 3, 5)

View file

@ -0,0 +1,13 @@
// Kotlin JS version 1.1.4-3
fun evalWithX(expr: String, a: Double, b: Double) {
var x = a
val atA = eval(expr)
x = b
val atB = eval(expr)
return atB - atA
}
fun main(args: Array<String>) {
println(evalWithX("Math.exp(x)", 0.0, 1.0))
}

View file

@ -0,0 +1,7 @@
expression$ = "x^2 - 7"
Print (EvaluateWithX(expression$, 5) - EvaluateWithX(expression$, 3))
End
Function EvaluateWithX(expression$, x)
EvaluateWithX = Eval(expression$)
End Function

View file

@ -0,0 +1,4 @@
code = loadstring"return x^2" --this doesn't really need to be input, does it?
val1 = setfenv(code, {x = io.read() + 0})()
val2 = setfenv(code, {x = io.read() + 0})()
print(val2 - val1)

View file

@ -0,0 +1,7 @@
env = {}
f = load("return x", nil, nil, env)
env.x = tonumber(io.read()) -- user enters 2
a = f()
env.x = tonumber(io.read()) -- user enters 3
b = f()
print(a + b) --> outputs 5

View file

@ -0,0 +1,7 @@
function r = calcit(f, val1, val2)
x = val1;
a = eval(f);
x = val2;
b = eval(f);
r = b-a;
end

View file

@ -0,0 +1,3 @@
Input source code is "10 x" , X is locally bound to 3 & 2 and the resulting expressions evaluated.
(10 x /. x -> 3 ) - (10 x /. x -> 2 )
-> 10

View file

@ -0,0 +1,7 @@
vardef evalit(expr s, va, vb) =
save x,a,b; x := va; a := scantokens s;
x := vb; b := scantokens s; a-b
enddef;
show(evalit("2x+1", 5, 3));
end

View file

@ -0,0 +1,6 @@
import macros, strformat
macro eval(s, x: static[string]): untyped =
parseStmt(&"let x={x}\n{s}")
echo(eval("x+1", "3.1"))

View file

@ -0,0 +1,8 @@
say evalWithX("x**2", 2)
say evalWithX("x**2", 3.1415926)
::routine evalWithX
use arg expression, x
-- X now has the value of the second argument
interpret "return" expression

View file

@ -0,0 +1,8 @@
declare
fun {EvalWithX Program A B}
{Compiler.evalExpression Program env('X':B) _}
-
{Compiler.evalExpression Program env('X':A) _}
end
in
{Show {EvalWithX "{Exp X}" 0.0 1.0}}

View file

@ -0,0 +1,2 @@
test(f,a,b)=f=eval(f);f(a)-f(b);
test("x->print(x);x^2-sin(x)",1,3)

View file

@ -0,0 +1,11 @@
<?php
function eval_with_x($code, $a, $b) {
$x = $a;
$first = eval($code);
$x = $b;
$second = eval($code);
return $second - $first;
}
echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>

View file

@ -0,0 +1,8 @@
sub eval_with_x
{my $code = shift;
my $x = shift;
my $first = eval $code;
$x = shift;
return eval($code) - $first;}
print eval_with_x('3 * $x', 5, 10), "\n"; # Prints "15".

View file

@ -0,0 +1,12 @@
(phixonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.1"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">include</span> <span style="color: #7060A8;">eval</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">eval_with_x</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">expr</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">eval</span><span style="color: #0000FF;">(</span><span style="color: #000000;">expr</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">},{{</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">}})[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">-</span>
<span style="color: #7060A8;">eval</span><span style="color: #0000FF;">(</span><span style="color: #000000;">expr</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">},{{</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">}})[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">eval_with_x</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"integer x = power(2,x)"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<!--

View file

@ -0,0 +1,12 @@
(let Expression '(+ X (* X X)) # Local expression
(println
(+
(let X 3
(eval Expression) )
(let X 4
(eval Expression) ) ) )
(let Function (list '(X) Expression) # Build a local function
(println
(+
(Function 3)
(Function 4) ) ) ) )

View file

@ -0,0 +1,11 @@
> int x=10;
Result: 10
> x * 5;
Result: 50
> dump wrapper
Last compiled wrapper:
001: mapping(string:mixed) ___hilfe = ___Hilfe->variables;
002: # 1
003: mixed ___HilfeWrapper() { return (([mapping(string:int)](mixed)___hilfe)->x) * 5; ; }
004:
>

View file

@ -0,0 +1,8 @@
string payload = "x * 5";
program demo = compile_string("string eval(mixed x){ " + payload + "; }");
demo()->eval(10);
Result: 50
demo()->eval(20);
Result: 100

View file

@ -0,0 +1,5 @@
>>> def eval_with_x(code, a, b):
return eval(code, {'x':b}) - eval(code, {'x':a})
>>> eval_with_x('2 ** x', 3, 5)
24

View file

@ -0,0 +1,9 @@
>>> def eval_with_args(code, **kwordargs):
return eval(code, kwordargs)
>>> code = '2 ** x'
>>> eval_with_args(code, x=5) - eval_with_args(code, x=3)
24
>>> code = '3 * x + y'
>>> eval_with_args(code, x=5, y=2) - eval_with_args(code, x=3, y=1)
7

View file

@ -0,0 +1,15 @@
evalWithAB <- function(expr, var, a, b) {
env <- new.env() # provide a separate env, so that the choosen
assign(var, a, envir=env) # var name do not collide with symbols inside
# this function (e.g. it could be even "env")
atA <- eval(parse(text=expr), env)
# and then evaluate the expression inside this
# ad hoc env-ironment
assign(var, b, envir=env)
atB <- eval(parse(text=expr), env)
return(atB - atA)
}
print(evalWithAB("2*x+1", "x", 5, 3))
print(evalWithAB("2*y+1", "y", 5, 3))
print(evalWithAB("2*y+1", "x", 5, 3)) # error: object "y" not found

View file

@ -0,0 +1,5 @@
prog: [x * 2]
fn: func [x] [do bind prog 'x]
a: fn 2
b: fn 4
subtract b a

View file

@ -0,0 +1,24 @@
/*REXX program demonstrates a run─time evaluation of an expression (entered at run─time)*/
say ' enter the 1st expression to be evaluated:'
parse pull x /*obtain an expression from the console*/
y.1= x /*save the provided expression for X. */
say
say ' enter the 2nd expression to be evaluated:'
parse pull x /*obtain an expression from the console*/
y.2= x /*save the provided expression for X. */
say
say ' 1st expression entered is: ' y.1
say ' 2nd expression entered is: ' y.2
say
interpret 'say " value of the difference is: "' y.2 "-" '('y.1")" /* ◄─────┐ */
/**/
/**/
/*subtract 1st exp. from the 2nd──►──┘ */
drop x /*X var. is no longer a global variable*/
exit 0 /*stick a fork in it, we're all done. */

View file

@ -0,0 +1,5 @@
#lang racket
(define ns (make-base-namespace))
(define (eval-with-x code a b)
(define (with v) (eval `(let ([x ',v]) ,code) ns))
(- (with b) (with a)))

View file

@ -0,0 +1,7 @@
#lang racket
(define ns (make-base-namespace))
(define (eval-with-x code a b)
(define (with v)
(namespace-set-variable-value! 'x v #f ns)
(eval code ns))
(- (with b) (with a)))

View file

@ -0,0 +1,5 @@
use MONKEY-SEE-NO-EVAL;
sub eval_with_x($code, *@x) { [R-] @x.map: -> \x { EVAL $code } }
say eval_with_x('3 * x', 5, 10); # Says "15".
say eval_with_x('3 * x', 5, 10, 50); # Says "105".

View file

@ -0,0 +1,7 @@
expression = "return pow(x,2) - 7"
one = evalwithx(expression, 1.2)
two = evalwithx(expression, 3.4)
see "one = " + one + nl + "two = " + two + nl
func evalwithx expr, x
return eval(expr)

View file

@ -0,0 +1,9 @@
def bind_x_to_value(x)
binding
end
def eval_with_x(code, a, b)
eval(code, bind_x_to_value(b)) - eval(code, bind_x_to_value(a))
end
puts eval_with_x('2 ** x', 3, 5) # Prints "24"

View file

@ -0,0 +1,6 @@
compiled = code(' define("triple(x)") :(a);triple triple = 3 * x :(return)') :<compiled>
a x = 1
first = triple(x)
x = 3
output = triple(x) - first
end

View file

@ -0,0 +1,6 @@
compiled = code(' define("triple()") :(a);triple triple = 3 * x :(return)') :<compiled>
a x = 1
first = triple(x)
x = 3
output = triple(x) - first
end

View file

@ -0,0 +1,8 @@
object Eval extends App {
def evalWithX(expr: String, a: Double, b: Double)=
{val x = b; eval(expr)} - {val x = a; eval(expr)}
println(evalWithX("Math.exp(x)", 0.0, 1.0))
}

View file

@ -0,0 +1,4 @@
(define (eval-with-x prog a b)
(let ((at-a (eval `(let ((x ',a)) ,prog)))
(at-b (eval `(let ((x ',b)) ,prog))))
(- at-b at-a)))

View file

@ -0,0 +1,7 @@
func eval_with_x(code, x, y) {
var f = eval(code);
x = y;
eval(code) - f;
}
say eval_with_x(x: 3, y: 5, code: '2 ** x'); # => 24

View file

@ -0,0 +1,264 @@
BEGIN
CLASS ENV;
BEGIN
CLASS ITEM(N, X); TEXT N; REAL X;
BEGIN
REF(ITEM) NEXT; NEXT :- HEAD; HEAD :- THIS ITEM;
END ITEM;
REF(ITEM) HEAD;
REF(ITEM) PROCEDURE LOOKUP(V); TEXT V;
BEGIN
REF(ITEM) I; BOOLEAN FOUND; I :- HEAD;
WHILE NOT FOUND DO
IF I == NONE OR ELSE I.N = V
THEN FOUND := TRUE
ELSE I :- I.NEXT;
LOOKUP :- I;
END LOOKUP;
REF(ENV) PROCEDURE SET(V, X); TEXT V; REAL X;
BEGIN
REF(ITEM) I; I :- LOOKUP(V);
IF I == NONE THEN I :- NEW ITEM(V, X) ELSE I.X := X;
SET :- THIS ENV;
END SET;
REAL PROCEDURE GET(V); TEXT V;
GET := LOOKUP(V).X;
END ENV;
CLASS EXPR(EV); REF(ENV) EV;
BEGIN
REAL PROCEDURE POP;
BEGIN
IF STACKPOS > 0 THEN
BEGIN STACKPOS := STACKPOS - 1; POP := STACK(STACKPOS); END;
END POP;
PROCEDURE PUSH(NEWTOP); REAL NEWTOP;
BEGIN
STACK(STACKPOS) := NEWTOP;
STACKPOS := STACKPOS + 1;
END PUSH;
REAL PROCEDURE CALC(OPERATOR, ERR); CHARACTER OPERATOR; LABEL ERR;
BEGIN
REAL X, Y; X := POP; Y := POP;
IF OPERATOR = '+' THEN PUSH(Y + X)
ELSE IF OPERATOR = '-' THEN PUSH(Y - X)
ELSE IF OPERATOR = '*' THEN PUSH(Y * X)
ELSE IF OPERATOR = '/' THEN BEGIN
IF X = 0 THEN
BEGIN
EVALUATEDERR :- "DIV BY ZERO";
GOTO ERR;
END;
PUSH(Y / X);
END
ELSE IF OPERATOR = '^' THEN PUSH(Y ** X)
ELSE
BEGIN
EVALUATEDERR :- "UNKNOWN OPERATOR";
GOTO ERR;
END
END CALC;
PROCEDURE READCHAR(CH); NAME CH; CHARACTER CH;
BEGIN
IF T.MORE THEN CH := T.GETCHAR ELSE CH := EOT;
END READCHAR;
PROCEDURE SKIPWHITESPACE(CH); NAME CH; CHARACTER CH;
BEGIN
WHILE (CH = SPACE) OR (CH = TAB) OR (CH = CR) OR (CH = LF) DO
READCHAR(CH);
END SKIPWHITESPACE;
PROCEDURE BUSYBOX(OP, ERR); INTEGER OP; LABEL ERR;
BEGIN
CHARACTER OPERATOR;
REAL NUMBR;
BOOLEAN NEGATIVE;
SKIPWHITESPACE(CH);
IF OP = EXPRESSION THEN
BEGIN
NEGATIVE := FALSE;
WHILE (CH = '+') OR (CH = '-') DO
BEGIN
IF CH = '-' THEN NEGATIVE := NOT NEGATIVE;
READCHAR(CH);
END;
BUSYBOX(TERM, ERR);
IF NEGATIVE THEN
BEGIN
NUMBR := POP; PUSH(0 - NUMBR);
END;
WHILE (CH = '+') OR (CH = '-') DO
BEGIN
OPERATOR := CH; READCHAR(CH);
BUSYBOX(TERM, ERR); CALC(OPERATOR, ERR);
END;
END
ELSE IF OP = TERM THEN
BEGIN
BUSYBOX(FACTOR, ERR);
WHILE (CH = '*') OR (CH = '/') DO
BEGIN
OPERATOR := CH; READCHAR(CH);
BUSYBOX(FACTOR, ERR); CALC(OPERATOR, ERR)
END
END
ELSE IF OP = FACTOR THEN
BEGIN
BUSYBOX(POWER, ERR);
WHILE CH = '^' DO
BEGIN
OPERATOR := CH; READCHAR(CH);
BUSYBOX(POWER, ERR); CALC(OPERATOR, ERR)
END
END
ELSE IF OP = POWER THEN
BEGIN
IF (CH = '+') OR (CH = '-') THEN
BUSYBOX(EXPRESSION, ERR)
ELSE IF (CH >= '0') AND (CH <= '9') THEN
BUSYBOX(NUMBER, ERR)
ELSE IF (CH >= 'A') AND (CH <= 'Z') THEN
BUSYBOX(VARIABLE, ERR)
ELSE IF CH = '(' THEN
BEGIN
READCHAR(CH);
BUSYBOX(EXPRESSION, ERR);
IF CH = ')' THEN READCHAR(CH) ELSE GOTO ERR;
END
ELSE GOTO ERR;
END
ELSE IF OP = VARIABLE THEN
BEGIN
TEXT VARNAM;
VARNAM :- BLANKS(32);
WHILE (CH >= 'A') AND (CH <= 'Z')
OR (CH >= '0') AND (CH <= '9') DO
BEGIN
VARNAM.PUTCHAR(CH);
READCHAR(CH);
END;
PUSH(EV.GET(VARNAM.STRIP));
END
ELSE IF OP = NUMBER THEN
BEGIN
NUMBR := 0;
WHILE (CH >= '0') AND (CH <= '9') DO
BEGIN
NUMBR := 10 * NUMBR + RANK(CH) - RANK('0'); READCHAR(CH);
END;
IF CH = '.' THEN
BEGIN
REAL FAKTOR;
READCHAR(CH);
FAKTOR := 10;
WHILE (CH >= '0') AND (CH <= '9') DO
BEGIN
NUMBR := NUMBR + (RANK(CH) - RANK('0')) / FAKTOR;
FAKTOR := 10 * FAKTOR;
READCHAR(CH);
END;
END;
PUSH(NUMBR);
END;
SKIPWHITESPACE(CH);
END BUSYBOX;
BOOLEAN PROCEDURE EVAL(INP); TEXT INP;
BEGIN
EVALUATEDERR :- NOTEXT;
STACKPOS := 0;
T :- COPY(INP.STRIP);
READCHAR(CH);
BUSYBOX(EXPRESSION, ERRORLABEL);
IF NOT T.MORE AND STACKPOS = 1 AND CH = EOT THEN
BEGIN
EVALUATED := POP;
EVAL := TRUE;
GOTO NOERRORLABEL;
END;
ERRORLABEL:
EVAL := FALSE;
IF EVALUATEDERR = NOTEXT THEN
EVALUATEDERR :- "INVALID EXPRESSION: " & INP;
NOERRORLABEL:
END EVAL;
REAL PROCEDURE RESULT;
RESULT := EVALUATED;
TEXT PROCEDURE ERR;
ERR :- EVALUATEDERR;
INTEGER EXPRESSION, TERM, FACTOR, POWER, NUMBER, VARIABLE;
CHARACTER TAB, LF, CR, SPACE, EOT, CH;
REAL ARRAY STACK(0:31);
INTEGER STACKPOS;
REAL EVALUATED;
TEXT EVALUATEDERR, T;
EXPRESSION := 1;
TERM := 2;
FACTOR := 3;
POWER := 4;
NUMBER := 5;
VARIABLE := 6;
TAB := CHAR(9);
LF := CHAR(10);
CR := CHAR(13);
SPACE := CHAR(32);
EOT := CHAR(0);
END EXPR;
REF(EXPR) EXA, EXB;
EXA :- NEW EXPR(NEW ENV.SET("X", 3));
EXB :- NEW EXPR(NEW ENV.SET("X", 5));
IF EXA.EVAL("2 ^ X") THEN
BEGIN
IF EXB.EVAL("2 ^ X")
THEN OUTFIX(EXB.RESULT - EXA.RESULT, 3, 10)
ELSE OUTTEXT(EXB.ERR)
END ELSE OUTTEXT(EXA.ERR);
OUTIMAGE;
END.

View file

@ -0,0 +1,12 @@
evalx(prog, a, b)
Func
Local x,eresult1,eresult2
a→x
expr(prog)→eresult1
b→x
expr(prog)→eresult2
Return eresult2-eresult1
EndFunc
■ evalx("^x", 0., 1)
1.71828

View file

@ -0,0 +1,5 @@
(defun eval-subtract-for-two-values-of-x (code-fragment x1 x0)
(- (eval ^(let ((x ,x1)) ,code-fragment))
(eval ^(let ((x ,x0)) ,code-fragment))))
(eval-subtract-for-two-values-of-x 1 2) ;; yields -4.67077427047161

View file

@ -0,0 +1,7 @@
(defun eval-subtract-for-two-values-of-x (code-fragment x1 x0)
(let ((e1 (make-env (list (cons 'x x1)))) ;; create two environments stuffed with binding for x
(e0 (make-env (list (cons 'x x0)))))
(- (eval code-fragment e1) ;; pass these environment to eval
(eval code-fragment e0))))
(eval-subtract-for-two-values-of-x '(exp x) 1 2)

View file

@ -0,0 +1,9 @@
(defun eval-subtract-for-two-values-of-x (code-fragment x1 x0)
(let ((e1 (make-env))
(e0 (make-env)))
(env-vbind e1 'x x1)
(env-vbind e0 'x x0)
(- (eval code-fragment e1)
(eval code-fragment e0))))
(eval-subtract-for-two-values-of-x '(exp x) 1 2)

View file

@ -0,0 +1,7 @@
(defvar x)
(defun eval-subtract-for-two-values-of-x (code-fragment x1 x0)
(- (let ((x x1)) (eval code-fragment))
(let ((x x0)) (eval code-fragment))))
(eval-subtract-for-two-values-of-x '(exp x) 1 2)

View file

@ -0,0 +1,9 @@
proc eval_twice {func a b} {
set x $a
set 1st [expr $func]
set x $b
set 2nd [expr $func]
expr {$2nd - $1st}
}
puts [eval_twice {2 ** $x} 3 5] ;# ==> 24

View file

@ -0,0 +1,4 @@
proc eval_with_x {code val1 val2} {
expr {[set x $val2; eval $code] - [set x $val1; eval $code]}
}
eval_with_x {expr {2**$x}} 3 5 ;# ==> 24

View file

@ -0,0 +1,7 @@
package require Tcl 8.5
proc eval_with {body a b} {
set lambda [list x $body]
expr {[apply $lambda $b] - [apply $lambda $a]}
}
eval_with {expr {2**$x}} 3 5 ;# ==> 24

View file

@ -0,0 +1,10 @@
#lang transd
MainModule: {
code: "(+ 5 x)",
_start: (lambda (textout
(- (to-Int (with x 100 (snd (eval code))))
(to-Int (with x 1 (snd (eval code)))))
))
}

View file

@ -0,0 +1,15 @@
eval_with_x() {
set -- "`x=$2; eval "$1"`" "`x=$3; eval "$1"`"
expr "$2" - "$1"
}
eval_with_x '
# compute 2 ** $x
p=1
while test $x -gt 0; do
p=`expr $p \* 2`
x=`expr $x - 1`
done
echo $p
' 3 5
# Prints '24'

View file

@ -0,0 +1,12 @@
import "meta" for Meta
var x
Meta.eval("x = 2")
System.print("First x = %(x)")
var y = x // save this value
Meta.eval("x = 5")
System.print("Second x = %(x)")
Meta.eval("x = x - y")
System.print("Delta x = %(x)")

View file

@ -0,0 +1,8 @@
fcn evalWithX(text,x) {
f:=Compiler.Compiler.compileText(text);
f.x = x; // set free var in compiled blob
f.__constructor(); // run blob
vm.regX // compiler sets the VMs X register for cases like this
}
const TEXT="var x; x*2"; // variables need to be declared
evalWithX(TEXT,5) - evalWithX(TEXT,3) #--> 4

View file

@ -0,0 +1,2 @@
var klass=Compiler.Compiler.compileText("var x; returnClass(x*2)");
(klass.__constructor(klass.x=5) - klass.__constructor(klass.x=3)).println();