Got it! This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
A stack is a list in which the following operations are available.
push or append an element on the stack
pop or remove an element off the stack
empty returns true if the stack is empty
top returns the top element (if not empty, otherwise null)
Note: Each programming language has one or more ways to accomplish these operations.
3. Stack-based code
A stack-based code (is a simple code execution model that) executes by traversing through the code and executing each element of the code using the stack.
Let us use our running logical expression example.
( X & Y ) | ( ( ! X ) & ( ! Y ) )
4. Logical expression
Note that in a postfix representation, the operator is traversed last. And, in evaluation, both operands are needed before the operator can be applied. So, by an induction argument, a postfix representation can be used as a stack-based code to determine the value of an expression, given the values of the logical variables.
5. Environment
A simple variable environment (without scope) can be implemented using a dictionary.
Suppose that x has the value 0 and that y has the value 1.
Here is a dictionary that could express this idea.
The environment of the logical variables can be represented as a dictionary. Here is an example for x with the value of 0 and y with the value of 1.
varDict1 = {
"x" : 0,
"y" : 1,
}
8. Execution code
function execute(codeList1,varDict1) {
var n1 = codeList1.length;
var stack1 = [];
for (var i1=0; i1 < n1; i1++) {
var code1 = codeList1[i1];
var type1 = code1[0];
var value1 = 0;;
if (type1 == "var") {
var name1 = code1[1];
value1 = varDict1[name1];
}
else if (type1 == "int") {
value1 = code1[1];
}
else if (type1 == "op1") {
var op1 = code1[1];
var y1 = stack1.pop();
if (op1 == "not") {
value1 = 1 - y1;
}
}
else if (type1 == "op2") {
var op2 = code1[1];
var y1 = stack1.pop();
var x1 = stack1.pop();
if (op2 == "and") {
value1 = x1 * y1;
}
else if (op2 == "or") {
value1 = x1 + y1 - x1*y1;
}
else if (op2 == "xor") {
value1 = (x1 + y1) % 2;
}
else if (op2 == "eqv") {
value1 = (x1 + y1 + 1) % 2;
}
}
stack1.push(value1);
}
return stack1[0];
}
9. Induction argument
An induction argument considers the various cases of the tree.
a leaf node: variable or integer
a binary operator interior node
a unary operator interior node
Each type of node leaves one value on the stack. When a submode is called, it leaves one item on the stack. One item for unary operators. Two items for binary operators.
Here is a code example, with print statements interspersed to trace what is happening.
Here is the JavaScript code.
Here is the output of the JavaScript code.
Note: How might we dynamically determine the values for the logical variables given a variable number of variables?