Created
January 8, 2009 15:07
-
-
Save youz/44750 to your computer and use it in GitHub Desktop.
brainf*ck interpreter
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
(defun bf (src &optional (tape-length 100)) | |
(let* ((code (remove-if-not (lambda (c) (find c "<>+-.,[]")) src)) | |
(len (length code)) | |
(jump (make-hash-table))) | |
(do* ((i 0 (1+ i)) (stack)) | |
((= i len) (when stack (error (format nil "unmatch [ at ~A" (car stack))))) | |
(case (aref code i) | |
(#\[ (push i stack)) | |
(#\] (unless stack (error (format nil "unmatch ] at ~A" i))) | |
(let ((j (pop stack))) | |
(setf (gethash j jump) i (gethash i jump) j))))) | |
(do* ((tape (make-array tape-length :initial-element 0)) | |
(pos 0) | |
(cur 0 (1+ cur))) | |
((= cur len) (values tape pos)) | |
(case (aref code cur) | |
(#\+ (incf #1=(aref tape pos))) | |
(#\- (decf #1#)) | |
(#\> (incf pos)) | |
(#\< (when (< (decf pos) 0) (error (format nil "address-error at ~A" cur)))) | |
(#\, (setf #1# (char-code (read-char)))) | |
(#\. (princ (code-char #1#))) | |
(#\[ (when (= 0 #1#) (setq cur #2=(gethash cur jump)))) | |
(#\] (when (> #1# 0) (setq cur #2#))))))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment