DrRacket is a functional programming language built in lisp.
I created an effectful function called run-ins
which take in an instruction
and make some changes to specified variables (I'm trying to re-create a working computer)
Now, I want to create another function, called run-loinst
id est: run a list of instrcutions, and this is the code:
(define (run-loinst loinst)
(map run-ins loinst))
As it turns out, when I run run-loinst
on a list of instructions with repeating terms, the repeated instructions are only run once, and it seems that the effect of an earlier list element will not take place before the running of a later term.
So, how can I write a code that would allow me to run multiple instructions and have their effects build on the effects of previous terms in sequential order?
(BTW, the below is the code of run-ins
and supporting function)
(define (run-ins ins)
(cond [(string=? (ins-type ins) "+")
(set-Rs! (second (ins-lori ins))
(+ (* (first (ins-low ins)) (first (ins-lori ins))) (second (ins-lori ins))))]
[(string=? (ins-type ins) "set")
(set-Rs! (second (ins-lori ins))
(* (first (ins-low ins)) (first (ins-lori ins))))]
[else void]))
(define (set-Rs! index val)
(local [(define (fn-1 n acc)
(if (= n (length Rs))
acc
(cond [(= index n) (fn-1 (add1 n) (append acc (list val)))]
[else (fn-1 (add1 n) (append acc (list (list-ref Rs n))))])))]
(set! Rs (fn-1 0 empty))))
If I'm understanding your code correctly, you're storing the state of the computer inside of the Instruction objects. Because of this, when you make a change to each Instruction object individually it has no effect on the later ones in the list. I would suggest instead to separate your state out from your instructions and use something like fold
.
If you have some function which takes an Instruction and machine state (in that order), runs the Instruction on that state, and returns the new state (lets call this function run
), you can run a list of Instructions on a given machine state like so:
(fold run current-state instructions-list)
And this will return the new state after running all the instructions.