Open
Conversation
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Write a small C program that is representative of a miniature
interpreter. The program
should take as input from file - a list, evaluate it and output the
result.
For eg:
(= a 1)
(= b 2)
(+ (* a b) 3)
The result of evaluation should be 5.
Note that the lists can be arbitrarily nested:
(+ (* a (- c d)) (* k x))
The program should gracefully handle nested lists.
Each element of this "list" is either an integer, a variable name, an
operator like +, -
or a list itself, that is, it's definition is recursive.
More formally:
list: element
| element list
element: number | variable | operator | '( list ')'
The above specification is called Context Free Grammar, which is a
mathematical notation of specifying language grammars [2].
For operators just consider the standard arithmetic operators: +, -, *, /,
Bonus points for multi-name variables like "foo", but single-letter
variables are also fine to
begin with.
Write the program in two parts:
a) The first part should correctly parse the input and build the
data-structure to represent the evaluation. This data structure is
called abstract syntax tree or AST for short [2].
b) In the second part, traverse the AST and evaluate the expression.
Note that a single AST should represent single expression.
For example: (= a (+ 2 3))
can be represented as following tree:
=
a +
2 3
The first phase should build this tree, and the second phase should
then do the tree-walk and evaluate the expression.
The notation of "lists" is more commonly known as s-expression [3] and
is the basis of functional languages like LISP. Make the program
robust. It should be able to deal
with incorrect syntax like
(+ 1) and gracefully exit with an error message.