我正在尝试为简单的2x2矩阵开发构造函数和选择器,但我不确定我所做的是否正确。这需要一个包含4个元素的列表并生成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)
这有效......但我不确定我是否正确使用选择器。
答案 0 :(得分:1)
你所做的是通过闭包实现对象的“通常”Scheme方式。您当然可以继续为选择器定义一些便利函数:
(define (get-place matrix ix) ((matrix 'get-place) ix)
(define (matrix->list matrix) ...)
我不确定我理解你对选择器“正确”使用的要求。毕竟,你已经知道它有效......