維傑 - 有計劃的最佳解決方案。但是,如果您真的要想通過永久更改列表來完成此項工作,則需要使用set-car!
和set-cdr!
。這是不是在計劃自然,需要幾個黑客,使其工作:
首先定義hand
和deck
:
(define hand '(dummy))
(define deck '((2 C) (3 H) (K D)))
hand
已開始與現有的元素,使其具有一定的現有列表結構進行修改。您無法使用set-car!
和set-cdr!
(零)('()
)。
現在寫draw
:
(define (draw from to)
; push the top element of `from` onto `to`
(set-cdr! to (copy to))
(set-car! to (car from))
; pop the top element of `from` off
(set-car! deck (cadr deck))
(set-cdr! deck (cddr deck)))
; also we need to define copy
(define (copy l)
(map (lambda (x) x) l))
這意味着你的手的最後一個元素將永遠是假的。這將是最好添加一個檢查的初步情況和覆蓋它,而不是推的:
(define (draw from to)
; push the top element of `from` onto `to` (just overwrite the first time)
(when (pair? (cdr to))
(set-cdr! to (copy to)))
(set-car! to (car from))
; pop the top element of `from` off
(set-car! deck (cadr deck))
(set-cdr! deck (cddr deck)))
您也應該檢查from
沒有做任何事情之前空。