Question

I'm trying to develop a constructor and selectors for a simple 2x2 matrix but I'm unsure if what I've made is correct. This takes a list with 4 elements and makes a 2x2:

(define matrix2x2
  (lambda (list)

    (define to-list list) ;returns the list form of this matrix
    (define get-place ;returns a place based on input row col
      (lambda (row col)
        (cond ((and (equal? row 1) (equal? col 1)) (car list))
              ((and (equal? row 1) (equal? col 2)) (car (cdr list)))
              ((and (equal? row 2) (equal? col 1)) (car (cdr (cdr list))))
              ((and (equal? row 2) (equal? col 2)) (car (cdr (cdr (cdr list)))))
              (else (display "no such place")))))

    (lambda (ret)
      (cond ((eq? ret 'get-place) get-place)
            ((eq? ret 'to-list) to-list)
            (else (error "Unknown request" ret))))))

;tests
(define my-matrix (m2x2 '(8 1 2 7)))
((my-matrix 'get-place) 2 2)
(my-matrix 'to-list)

This works... but I'm not sure I'm using selectors properly.

Was it helpful?

Solution

What you've done is the "usual" Scheme way of implementing objects via closures. You could of course go on to define some convenience functions for the selectors:

(define (get-place matrix ix) ((matrix 'get-place) ix)
(define (matrix->list matrix) ...)

I'm not sure I understand what you're asking about the "proper" use of selectors. After all, you already know that it works ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top