Skip to content

Instantly share code, notes, and snippets.

@theblacksquid
Last active July 6, 2016 00:04
Show Gist options
  • Save theblacksquid/22300eddb174971a8d24b5dd1b6cce0d to your computer and use it in GitHub Desktop.
Save theblacksquid/22300eddb174971a8d24b5dd1b6cce0d to your computer and use it in GitHub Desktop.
trying to implement an parser, stack and evaluator
(define stack
(let ((stk '()))
(lambda (msg . args)
(case msg
((peek) (car stk))
((push) (set! stk (cons (car args) stk)))
((pop) (let ((result (car stk))
(popped (cdr stk)))
(set! stk popped)
result))
((all) stk)
((empty?) (null? stk))
(else 'BAD-MESSAGE)))))
(define operands
'(("+" . "+")
("-" . "-")
("*" . "*")
("/" . "/")
("^" . "expt")
("%" . "mod")))
(define (operand? item)
(or (eqv? item "+")
(eqv? item "-")
(eqv? item "*")
(eqv? item "/")
(eqv? item "^")
(eqv? item "%")))
(define (space? item)
(eqv? item #\space))
(define (char->string c)
(make-string 1 c))
(define (string-split str)
(let loop ((ls (string->list str))
(result '())
(word '()))
(cond ((null? ls)
(reverse (cons (list->string (reverse word))
result)))
((eqv? (car ls) #\space)
(loop (cdr ls)
(cons (list->string (reverse word)) result)
'()))
(else (loop (cdr ls) result (cons (car ls) word))))))
(define (force-string num)
(if (string? num) num
(number->string num)))
(define (parse str) ;; might be having problems with
(let loop ((x-stack stack) ;; execution order
(tree (if (string? str) ;; TODO: Implement rpn s-exps
(string-split str)
str)))
(cond
((null? tree) (if (number? (car (x-stack 'all)))
(car (x-stack 'all))
(string->number (car (x-stack 'all)))))
((operand? (car tree))
(let ((oper (car tree))
(oprd1 (x-stack 'pop))
(oprd2 (x-stack 'pop)))
(begin
(x-stack 'push
(eval (list (string->symbol (cdr (assoc oper operands)))
(if (number? oprd1) oprd1
(string->number oprd1))
(if (number? oprd2) oprd2
(string->number oprd2)))))
(loop x-stack (cdr tree)))))
(else (begin
(x-stack 'push (car tree))
(print (x-stack 'all))
(loop x-stack
(cdr tree)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment