Skip to content

Instantly share code, notes, and snippets.

@dz1984
Last active June 30, 2017 22:17
Show Gist options
  • Save dz1984/f3716589bdc98fddaf6b9474239ba443 to your computer and use it in GitHub Desktop.
Save dz1984/f3716589bdc98fddaf6b9474239ba443 to your computer and use it in GitHub Desktop.
A simple brainfuck interpreter in Scheme.
#lang racket
(define-syntax incf
(syntax-rules ()
((_ x) (begin (set! x (+ x 1)) x))
((_ x i) (begin (set! x (+ x i)) x))))
(define-syntax decf
(syntax-rules ()
((_ x) (begin (set! x (- x 1)) x))
((_ x i) (begin (set! x (- x i)) x))))
(define (interpreter instruction)
(let ((i 0) (ptr 0) (mem (make-vector 20 0)) (end (string-length instruction)))
(do ((i 0 (incf i)))
((= i end))
(let ((current-instruction (string-ref instruction i)))
(case current-instruction
((#\>) (incf ptr))
((#\<) (decf ptr))
((#\-) (vector-set! mem ptr (- (vector-ref mem ptr) 1)))
((#\+) (vector-set! mem ptr (+ (vector-ref mem ptr) 1)))
((#\.) (write-byte (vector-ref mem ptr)))
((#\,) (vector-set! mem ptr (read-byte)))
((#\[) (if (zero? (vector-ref mem ptr))
(let ((loop 1))
(do()
((zero? loop))
(incf i)
(let ((current-instruction (string-ref instruction i)))
(if (eq? #\] current-instruction) (decf loop) '())
(if (eq? #\[ current-instruction) (incf loop) '()))))
'() ))
((#\]) (if (zero? (vector-ref mem ptr))
'()
(let ((loop 1))
(do()
((zero? loop))
(decf i)
(let ((current-instruction (string-ref instruction i)))
(if (eq? #\[ current-instruction) (decf loop) '())
(if (eq? #\] current-instruction) (incf loop) '()))))))
(else 'fail)
)
)
))
)
(interpreter "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment