Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;;;No known bugs
- (defun simplify (code); code is a string
- (loop with returncode = ""
- for char across code
- if (not (position char "><+-.,[]"))
- do (progn)
- else
- do (setf returncode (concatenate 'string returncode (coerce `(,char) 'string)))
- finally (return returncode)))
- (defun matching-closing (code instruction-pointer)
- (loop with counter = 0
- for char from 0 to (1- (- (length code) instruction-pointer ))
- when (equal (elt (subseq code instruction-pointer) char) #\[)
- do (incf counter)
- when (and (not (zerop counter)) (equal (elt (subseq code instruction-pointer) char) #\]))
- do (decf counter)
- when (and (zerop counter) (equal (elt (subseq code instruction-pointer) char) #\]))
- return (+ instruction-pointer char)))
- (defun main (code)
- (setf code (simplify code))
- (let ((memory (make-array (expt 10 5) :adjustable t :initial-element 0)) (data-pointer (/ (expt 10 5) 2)))
- (loop with stack = '()
- :for instruction-pointer from 0 :to (1- (length code)) :do
- (case (elt code instruction-pointer)
- (#\> (incf data-pointer))
- (#\< (decf data-pointer))
- (#\+ (incf (aref memory data-pointer)))
- (#\- (decf (aref memory data-pointer)))
- (#\. (princ (coerce `(,(code-char (aref memory data-pointer))) 'string)))
- (#\, (setf (aref memory data-pointer) (char-code (read-char))))
- (#\[ (if (zerop (aref memory data-pointer))
- (setf instruction-pointer (matching-closing code instruction-pointer))
- (push instruction-pointer stack)))
- (#\] (if (not (zerop (aref memory data-pointer)))
- (setf instruction-pointer (1- (pop stack)))
- (pop stack)))))))
- (defun read-file (file) ; Just a simple function to read from a file and return all of it's contents as a string. Used to read bf programs from files.
- (let ((return-string ""))
- (with-open-file (stream file)
- (loop :for line = (read-line stream nil 'foo)
- :until (eq line 'foo)
- :do (setf return-string (concatenate 'string return-string line))
- :finally (return return-string)))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement