Advertisement
Guest User

Untitled

a guest
Jun 26th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. ;;; A grid is is an abstract object that holds `items` at each
  2. ;;; `coordinate`. In particular, n x m grid consists of lattice points
  3. ;;; (x,y) where 0 ≤ x < n and 0 ≤ y < m.
  4. ;;; At each coordinate (x,y) contains an object.
  5.  
  6. (define (make-grid n m)
  7. ;; add a test whether n ≥ 1 and m ≥ 1
  8. (let ([grid (make-vector (* m n) '())])
  9.  
  10. (define (position->index i j)
  11. (+ j (* i m)))
  12.  
  13. (define (get-coordinates i j)
  14. (vector-ref grid (position->index i j)))
  15.  
  16. (define (get-self) grid)
  17.  
  18. (define (populate-with f)
  19. (for* ([i n]
  20. [j m])
  21. (vector-set! grid (position->index i j) (f i j))))
  22.  
  23. (define (set-coordinates i j val)
  24. (vector-set! grid (position->index i j) val))
  25.  
  26. (case-lambda
  27. [(cmd)
  28. (cond
  29. [(eq? cmd 'get) grid]
  30. [else (error "make-grid, unknown command")])]
  31. ;;
  32. [(i j)
  33. (cond
  34. [(and (integer? i) (integer? j)) (get-coordinates i j)]
  35. [(and (eq? i 'populate-using) (procedure? j)) (populate-with j)]
  36. [(eq? i 'populate-constant) (populate-with (lambda (x y) j))])]
  37.  
  38. [(i j val)
  39. (cond
  40. [(and (integer? i) (integer? j)) (set-coordinates i j val)])]
  41. )))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement