Created
August 26, 2018 19:55
-
-
Save blippy/ccaec3bb9f61d935b4c24b4665943968 to your computer and use it in GitHub Desktop.
Micro assembly using scheme
This file contains hidden or 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
| ;;(load "mass.scm") | |
| (require-extension anaphora) | |
| (require-extension holes) | |
| (require-extension s) | |
| (require-extension srfi-69) | |
| (define program "MOV a 3 | |
| ADD a a -1 | |
| JNE 1 a 1") | |
| ;;; extract assembly instructions from the program | |
| ;;; s-split splits the instruction by space | |
| ;;; s-lines splits the program by line | |
| (define asses (map (@> s-split " ") (s-lines program))) | |
| (define registers (make-hash-table)) | |
| (define (set-dest register value) | |
| (hash-table-set! registers register value)) | |
| (define (get-src key) | |
| (aif (string->number key) ; try to convert string to number | |
| it ; succeeded. It must have been a number | |
| (hash-table-ref/default registers key 0))) ; must have been a register | |
| ;;; define the actions for an instruction | |
| (define (MOV dest src) | |
| (set-dest dest (get-src src))) | |
| (define (ADD dest src1 src2) | |
| (set-dest dest (+ (get-src src1) (get-src src2)))) | |
| (define (SUB dest src1 src2) | |
| (set-dest dest (- (get-src src1) (get-src src2)))) | |
| (define (JNE address src1 src2) | |
| (if (= (get-src src1) (get-src src2)) | |
| #f ; no branching required, so just return false | |
| (string->number address))) ; branch required, return the address | |
| ;; run the machine | |
| (let loop ((pc 0)) ; pc is the program counter | |
| (when (< pc (length asses)) ; keep running until the pc goes out of bounds | |
| (define ass (list-ref asses pc)) ; retrieve the instruction | |
| (define args (cdr ass)) ; ; the arguments of the instruction | |
| (case (string->symbol (car ass)) ; extract the command to be performed | |
| [(MOV) (apply MOV args)] | |
| [(ADD) (apply ADD args)] | |
| [(SUB) (apply SUB args)] | |
| [(JNE) (awhen (apply JNE args) (loop it))] | |
| [else (print "didn't understand instruction")]) | |
| (loop (+ 1 pc)))) | |
| (display "Register dump:") | |
| (write (hash-table->alist registers)) | |
| (newline) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A puzzle set in CodinGame.