Vijay has the best solution for Scheme. However, if you really want to make this work by changing the lists permanently, you'll need to use set-car!
and set-cdr!
. This is not natural in Scheme, and requires a couple of hacks to make it work:
First define hand
and deck
:
(define hand '(dummy))
(define deck '((2 C) (3 H) (K D)))
hand
has to start with an existing element so that it has some existing list structure to modify. You can't use set-car!
and set-cdr!
with nil ( '()
).
Now write 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))
This means the last element of your hand will always be dummy. It would be better to add a check for the initial case and overwrite it instead of pushing:
(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)))
Also you should check that from
isn't empty before doing anything.