Question

In: Computer Science

Using the descriptions below, write a scanner for numbers, symbols, comments, arithmetic operators, and parenthesis in...

Using the descriptions below, write a scanner for numbers, symbols, comments, arithmetic operators, and parenthesis in Racket or scheme.

- a number is

one or more digits |

zero of more digits followed by a decimal point followed by one or more digits |

one or more digits followed by a decimal point followed by zero or more digits



- a symbol is
     one or more characters from the set [_A-Za-z] followed by zero or more characters from the set [_A-Za-z0-9]

- a comment is
     the literal string "#" followed by zero or more characters until the end of the line


- an arithmetic operator is
     + |
     - |
     * |
     /

- a parenthesis is
     ( |
     )


Your scanner must convert input text into the following tokens: NUM, SYM, ADD, SUBTRACT, MULTIPLY, DIVIDE, LPAREN, RPAREN, ERROR. Turn in your scanner implementations and test cases. Your test cases should show that your scanner produces a correct list of tokens when given valid input and the scanner output should contain an ERROR token when given invalid input. the output must all be list containing each output token.

Sample Racket return value from scanner: (NUM NUM NUM ADD NUM MULTIPLY NUM ADD NUM EOF) or (NUM NUM NUM ERROR NUM MULTIPLY NUM ADD NUM EOF)

For Racket, you may use the parser-tools/lex library that comes with Racket.

Solutions

Expert Solution

lang racket
;;; IMPORT
;; Import the lexer tools 
(require parser-tools/yacc
         parser-tools/lex
         (prefix-in : parser-tools/lex-sre)  ; names from lex-sre are prefixed with :
         ;                                     to avoid name collisions
         syntax/readerr)

;;; REGULAR EXPRESSIONS

;; Names for regular expressions matching letters and digits.
;; Note that :or are prefixed with a : due to (prefix-in : ...) above
(define-lex-abbrevs
  [letter     (:or (:/ "a" "z") (:/ #\A #\Z) )]
  [digit      (:/ #\0 #\9)])

;;; TOKENS

;; Tokens such as numbers (and identifiers and strings) carry a value
;; In the example only the NUMBER token is used, but you may need more.
(define-tokens value-tokens (NUMBER IDENTIFIER STRING))

;; Tokens that don't carry a value.
(define-empty-tokens op-tokens (newline :=  = < > + - * / ^  EOF))

;;; LEXER

;; Here the lexer (aka the scanner) is defined.
;; The construct lexer-src-pos evaluates to a function which scans an input port
;; returning one position-token at a time.

;; A position token contains besides the actual token also source location information
;; (i.e. you can see where in the file the token was read)

(define lex
  (lexer-src-pos
   [(eof)                                            ; input: eof of file     
    'EOF]                                            ; output: the symbol EOF

   [(:or #\tab #\space #\newline)                    ; input: whitespace
    (return-without-pos (lex input-port))]           ; output: the next token
   ;                                                           (i.e. skip the whitespace)

   [#\newline                                        ; input: newline
    (token-newline)]                                 ; ouput: a newline-token   
   ;                                                 ; note:  (token-newline) returns 'newline

   [(:or ":=" "+" "-" "*" "/" "^" "<" ">" "=")       ; input:  an operator
    (string->symbol lexeme)]                         ; output: corresponding symbol

   [(:+ digit)                                       ; input:  digits
    (token-NUMBER (string->number lexeme))]))        ; outout: a NUMBER token whose value is
;                                                    ;         the number
;                                                    ; note:   (token-value token)
;                                                              returns the number

;;; TEST

(define input (open-input-string "123+456"))

(lex input) ; (position-token (token 'NUMBER 123) (position 1 #f #f) (position 4 #f #f))
(lex input) ; (position-token '+ (position 4 #f #f) (position 5 #f #f))
(lex input) ; (position-token (token 'NUMBER 456) (position 5 #f #f) (position 8 #f #f))
(lex input) ; (position-token 'EOF (position 8 #f #f) (position 8 #f #f))


;; Let's make it a little easier to play with the lexer.

(define (string->tokens s)
  (port->tokens (open-input-string s)))

(define (port->tokens in)
  (define token (lex in))
  (if (eq? (position-token-token token) 'EOF)
      '()
      (cons token (port->tokens in))))

(map position-token-token (string->tokens "123*45/3"))   ; strip positions
; Output:

; (list (token 'NUMBER 123)
;        '*
;        (token 'NUMBER 45)
;        '/
;        (token 'NUMBER 3))

Related Solutions

USING C++: Consider the precedence levels of the relational, logical, and arithmetic operators of the PySub...
USING C++: Consider the precedence levels of the relational, logical, and arithmetic operators of the PySub language to be as follows (NOTE: 5 has highest precedence and 0 lowest): 5 *, /, % 4 +, - 3 <, <=, >, >=, !=, == 2 not 1 and 0 or 1.  Infix-Postfix Conversion and Evaluation with Logical and Relational operators – Convert the following infix expression to a postfix expression and evaluate the result (assume that true=1 and false=0). Provide both the...
using python without external libaries Using integer arithmetic operators '+' and '-', print all combinations that...
using python without external libaries Using integer arithmetic operators '+' and '-', print all combinations that sum up to 'sum' by inserting the operators between digits in 'number'. example for 'number=123456789' and 'sum = 0' Print the output using the terminal: Output should be exactly like this from 1 - 22 1 : +1+2-34-56+78+9=0 2 : +1-2-34+5+6+7+8+9=0 3 : +1-23-4-56-7+89=0 ... 12 : -1+2+34-5-6-7-8-9=0 13 : -1+23+4+56+7-89=0 14 : -1-2+34+56-78-9=0 ... 22 : -12-34+56+7-8-9=0
Write a balanced chemical equation for each of the following descriptions of chemical reactions, including state symbols:
Write a balanced chemical equation for each of the following descriptions of chemical reactions, including state symbols:a. Aluminum metal reacts with aqueous iron(II) chloride to form aqueous aluminum chloride and iron metal.b. Solid cobalt (III) oxide reacts with solid carbon to produce solid cobalt and carbon dioxide gas.c. Nitrogen dioxide gas reacts with gaseous oxygen and liquid water to form aqueous nitric acid.
Write a program to validate parenthesis of any given equation by using the following criteria (you...
Write a program to validate parenthesis of any given equation by using the following criteria (you MUST use stacks); Number of open parenthesis “(“must be same as number of close parentheses “)” For example if I input “3 + 4 * (98+34*(34+8)*34*(3+x)” the program should display an error message, because number of open parenthesis “(“is 3 and number of closed “)” parenthesis is 2. Stack-Driver.cpp: #include "stack.h" #include "stack.cpp" #include<stdio.h> #include<stdlib.h> #include<time.h> int main() {    stack<int> my_stack(100);    srand(time(NULL));...
Based on the descriptions given below, write the JavaScript codes to calculate the amount to be...
Based on the descriptions given below, write the JavaScript codes to calculate the amount to be paid for books purchased.  Declare all the variables used in this program.  Ask the user to key-in the book code using a prompt() method. Store the value in a variable named book_code.  Ask the user to key-in the number of books purchased using a prompt() method. Store the value in a variable named book_qty.  Ask the user whether they have...
The Hypothesis Test for One Mean 5) Using the proper symbols, write the null and alternative...
The Hypothesis Test for One Mean 5) Using the proper symbols, write the null and alternative hypotheses for each scenario below. (2 points each) a) In 1920, the average age men got married for the first time was 24.6 years. It is believed that young people are waiting longer to get married. A recent study of 120 men found that the average age the men got married for the first time was 29.5 years with a standard deviation of 5.2...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix expression. For example, 1 + 2 * 3 becomes 2 3 * 1 +. Also, evaluate the expression to ensure the expression is correct.
Your task is to take the below code, and insert comments (using the “%” symbol) next...
Your task is to take the below code, and insert comments (using the “%” symbol) next to each line of code to make sure that you know what every line does. clc clear close all NMax = 100; partialSum = 0; exactAnswer = pi^2; for k=1:NMax partialSum = partialSum + 6/k^2; percentDiff(k) = abs(partialSum - exactAnswer)/exactAnswer*100; end NVector = [1:NMax]; plot(NVector,percentDiff); xlabel('{{Noob}}'); ylabel('% Difference');
Match the descriptions below with the correct answer, using the letter codes shown in the table...
Match the descriptions below with the correct answer, using the letter codes shown in the table below. (8 points) A.    Realizable value B.    Percentage of receivables method C.      1/10, n/60 D.    Bad debt Expense E.      Aging of receivables F.       Direct write-off method G.     Operating cycle H.     Specific identification method I.        FOB shipping point J.        Time period assumption K.    n/10 EOM L.    Percentage of sales method M.   Permanent accounts N.    2/10, EOM O.    2/10, n/30 P.     FOB destination The economic life...
Objectives: Write a program which reads User Input using Scanner Print formatted output using printf or...
Objectives: Write a program which reads User Input using Scanner Print formatted output using printf or DecimalFormat Practice programming simple mathematical calculations Instructions: Samwise Gamgee has finally decided to submit his expense report for all of his adventures regarding his travels to Mordor. Part of those expenses are his stay at the Prancing Pony Inn located in Bree. You are to write a simple Java program which will generate an Invoice for his stay at the Inn. Your program should...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT