Created
June 18, 2011 18:00
-
-
Save jamiltron/1033340 to your computer and use it in GitHub Desktop.
Tiny Forsight, trying to figure out error
This file contains 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
#lang racket | |
(define *prompt* "> ") | |
(define *dictionary* '(("+" add-f))) | |
(define (push item stack) | |
(cons item stack)) | |
(define (pop stack) | |
(rest stack)) | |
(define (pop-2 stack) | |
(rest (rest stack))) | |
(define (mk-binary op) | |
(lambda (stack) | |
(push | |
(op (second stack) (first stack)) | |
(pop-2 stack)))) | |
(define add-f (mk-binary +)) | |
(define (tokenize str) | |
(define (splitter str i last stop sep) | |
(cond | |
((eq? i stop) | |
(cons (substring str last stop) '())) | |
((equal? (string-ref str i) sep) | |
(cons (substring str last i) (splitter str (+ i 1) (+ i 1) stop sep))) | |
(else | |
(splitter str (+ i 1) last stop sep)))) | |
(splitter str 0 0 (string-length str) #\space)) | |
(define (dict-get key dict) | |
(cond | |
((null? dict) | |
#f) | |
((equal? key (first (first dict))) | |
(first (rest (first dict)))) | |
(else | |
(dict-get key (rest dict))))) | |
(define (interpret-f input d-stack) | |
(cond | |
((null? input) | |
d-stack) | |
((string->number (first input)) | |
(interpret-f (rest input) (push (string->number (first input)) d-stack))) | |
(else | |
(let ((fun-f (dict-get (first input) *dictionary*))) | |
(interpret-f (rest input) ((eval fun-f) d-stack)))))) | |
(define (repl-f d-stack) | |
(display *prompt*) | |
(let* ((input (read-line)) | |
(new-stack (interpret-f (tokenize input) d-stack))) | |
(repl-f new-stack))) | |
(repl-f '()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment