Runtime evaluation/In an environment: Difference between revisions
Content added Content deleted
(Scala solution added) |
(Add Factor example) |
||
Line 249: | Line 249: | ||
1 |
1 |
||
</pre> |
</pre> |
||
=={{header|Factor}}== |
|||
Being a stack-based language, there is no need to bind data stack objects to a variable name. This is the idiomatic way to do it, with <code>eval</code> referencing what it needs from the data stack: |
|||
<lang factor>USE: eval |
|||
: eval-bi@- ( a b program -- n ) |
|||
tuck [ ( y -- z ) eval ] 2bi@ - ;</lang> |
|||
<lang factor>IN: scratchpad 9 4 "dup *" eval-bi@- . |
|||
65</lang> |
|||
Also note that, since programs are first-class denizens in Factor, the use cases for <code>eval</code> are few. Normally, you would pass in a program as a quotation: |
|||
<lang factor>: bi@- ( a b quot -- n ) bi@ - ; inline</lang> |
|||
<lang factor>IN: scratchpad 9 4 [ dup * ] bi@- . |
|||
65</lang> |
|||
However, to be pedantic about it, we can adhere to the letter of the task. Note that although we are using a dynamic variable for x, it exists in a temporary, non-global namespace. As far as I can tell, <code>eval</code> is unaware of surrounding lexical scope. |
|||
<lang factor>SYMBOL: x |
|||
: eval-with-x ( a b program -- n ) |
|||
tuck |
|||
[ [ x ] dip [ ( -- y ) eval ] curry with-variable ] 2bi@ - ;</lang> |
|||
<lang factor>IN: scratchpad "x get dup * " eval-with-x . |
|||
65</lang> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |