Created
October 15, 2020 22:24
-
-
Save bjjb/86ea5b85c0015e48fb624a913e8ecca1 to your computer and use it in GitHub Desktop.
A Common Lisp solution for the Mars Rover exercise
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
;;; Mars Rover | |
(defun move (rover cmd) | |
(let ((compass '(NORTH EAST SOUTH WEST))) | |
(let ((x (caar rover)) | |
(y (cadar rover)) | |
(h (cadr rover))) | |
(let ((dd (case cmd ('F 1) ('B -1) (otherwise 0))) | |
(dh (case cmd ('R 1) ('L -1) (otherwise 0))) | |
(dx (case h ('EAST 1) ('WEST -1) (otherwise 0))) | |
(dy (case h ('NORTH 1) ('SOUTH -1) (otherwise 0)))) | |
(list | |
(list (+ x (* dd dx)) (+ y (* dd dy))) | |
(nth (mod (+ (position h compass) dh) (length compass)) compass)))))) | |
(defun instruct (rover instructions) | |
(if (null instructions) | |
rover | |
(instruct (move rover (car instructions)) (cdr instructions)))) | |
(defun command (rover cmd) | |
(let ((convert (lambda (c) (intern (string (char-upcase c)))))) | |
(let ((instructions (mapcar convert (coerce cmd 'list)))) | |
(instruct rover instructions)))) | |
(assert (equal '((0 0) EAST) (move '((0 0) NORTH) 'R))) | |
(assert (equal '((6 4) NORTH) (instruct '((4 2) EAST) '(F L F F F R F L B)))) | |
(assert (equal '((6 4) NORTH) (command '((4 2) EAST) "FLFFFRFLB"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment