coords-operations.scm 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. (define-module (coords-operations)
  2. #:export
  3. (index->coords
  4. coords->index))
  5. (use-modules
  6. ((coords-model) #:prefix cm:))
  7. (define (index->coords index row-count col-count)
  8. #;(display (simple-format #f "index->coords ~a ~a ~a\n"
  9. index row-count col-count))
  10. (cond [(>= index (* row-count col-count))
  11. (throw 'index-error
  12. (simple-format #f "expected index < ~a" (* row-count col-count))
  13. index row-count col-count)]
  14. [(not (and (exact-integer? index)
  15. (>= index 0)))
  16. (throw 'index-error
  17. "expected index to be exact positive integer or exact integer 0"
  18. index)]
  19. [(let* ([row-coord (floor (/ index col-count))]
  20. [col-coord (- index (* row-coord col-count))])
  21. (cm:make-coords row-coord col-coord))]))
  22. (define (coords->index row-coord col-coord
  23. row-count col-count)
  24. (cond [(or (< row-coord 0)
  25. (< col-coord 0)
  26. (>= row-coord row-count)
  27. (>= col-coord col-count))
  28. (throw 'index-error "index out of bounds" row-coord col-coord row-count col-count)]
  29. [else (+ (* row-coord col-count) col-coord)]))