views:

58

answers:

1

I am trying to make a memory system where you input something in a slot of memory. So what I am doing is making an Alist and the car of the pairs is the memory location and the cdr is the val. I need the program to understand two messages, Read and Write. Read just displaying the memory location selected and the val that is assigned to that location and write changes the val of the location or address. How do I make my code so it reads the location you want it to and write to the location you want it to? Feel free to test this yourself. Any help would be much appreciated. This is what I have:

(define make-memory
  (lambda (n)
    (letrec ((mem '())
             (dump (display mem)))
      (lambda ()
        (if (= n 0)
            (cons (cons n 0) mem) mem)
            (cons (cons (- n 1) 0) mem))
      (lambda (msg loc val)
        (cond
          ((equal? msg 'read) (display 
                               (cons n val))(set! n (- n 1)))
          ((equal? msg 'write) (set! mem 
                                     (cons val loc)) (set! n (- n 1)) (display mem)))))))


(define mymem (make-memory 100))
+2  A: 

A possible solution:

(define (make-memory n)
  (let ([memory  (make-vector n 0)]
        [protect (lambda (addr) 
                   (if (and (addr . >= . 0) (addr . < . n)) 
                     addr 
                     (error "access to outside of memory")))])
    (match-lambda*
     [`(read  ,addr)    (cons addr (vector-ref memory (protect addr)))]
     [`(write ,addr ,x) (vector-set! memory (protect addr) x)])))

This has the added benefit of not using alists (for speed) and protecting against malicious attempts to access stuff outside the preallocated range ;). Works as desired:

> (define mem (make-memory 10))
> (mem 'read 0)
(0 . 0)
> (mem 'read 2)
(2 . 0)
> (mem 'write 2 10)
> (mem 'read 2)
(2 . 10)
> (mem 'read 100)
access to outside of memory

This might be a bit hard to grasp if you're just starting out with Scheme. You can read more about match-lambda and friends here. Vectors are Scheme's equivalent of arrays in other languages (read this).

Felix Lange