Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I tried to prepare an answer that's suitable for the question.</p> <p>I'm going to assume that all the stuff like <code>up(3)</code> was really supposed to be s-expressions like <code>(up 3)</code>. If not, too bad.</p> <p>You didn't say what the desired output of your example was. I'm going to hope my math is OK and stipulate that it's position (14 -7).</p> <p>The problem seemed to assume that only programs starting with <code>(move (0 0) ...)</code> are legal. I seized that assumption; I ain't letting go.</p> <p>With that prelude, I present my interpretation of the homework exercise:</p> <p><strong>The Horrible Little Love Child of <code>printf</code> and <code>eval</code></strong>.</p> <pre><code>#lang racket ;; the current position and functions to move it (struct pos (x y) #:transparent) (define the-pos (make-parameter (pos 0 0))) (define (dx f n) (match (the-pos) [(pos x y) (the-pos (pos (f x n) y))])) (define (dy f n) (match (the-pos) [(pos x y) (the-pos (pos x (f y n)))])) (define (left n) (dx - n)) (define (right n) (dx + n)) (define (up n) (dy - n)) (define (down n) (dy + n)) ;; namespace for `eval` (define-namespace-anchor a) (define ns (namespace-anchor-&gt;namespace a)) ;; start holding your nose (define (run str . args) (define as (for/list ([a args]) (read (open-input-string a)))) (match (read (open-input-string str)) [`(move (0 0) ,xs ...) (for ([x xs]) (define n (match (symbol-&gt;string x) [(pregexp "^arg(\\d)$" (list _ n)) (string-&gt;number n)] [else (error 'run "bad argN")])) (unless (&lt; -1 n (length as)) (error 'run "bad argN")) (eval (list-ref as n) ns)) (eval '(the-pos) ns)])) ;; a unit test to confirm our true evi^Hal (require rackunit) (the-pos (pos 0 0)) (check-equal? (run "(move (0 0) arg0 arg1 arg2 arg3 arg4 arg5 arg6)" "(up 3)" "(right 5)" "(right 4)" "(down 2)" "(up 6)" "(right 2)" "(right 3)") (pos 14 -7)) ;; and since we went through all the argN nonsense, the reverse: (the-pos (pos 0 0)) (check-equal? (run "(move (0 0) arg6 arg5 arg4 arg3 arg2 arg1 arg0)" "(right 3)" "(right 2)" "(up 6)" "(down 2)" "(right 4)" "(right 5)" "(up 3)") (pos 14 -7)) ;; not that it matters with addition and subtraction...why am I even... </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload