3

I want to add an integer to a list that already exists using Racket. Here is the code that I have so far.

(define (countBlackPegs gameList playerList)
(define blackPegs '())

(if (equal? (car playerList) (car gameList)) 
  (set! blackPegs '(1))
;;otherwise
  (set! blackPegs '(0)))
)

In theory I should be able to repeat the if statement (examining a different part of the list each time) and then append the blackPegs list with the appropriate value based on the result of the if statement. Unfortunately every append function I have tried doesn't work correctly. Any help would be appreciated.

4

1 回答 1

5

如果您想修改(使用set!)已经存在的列表,请按照以下方式执行操作,以便在开头添加新元素:

(set! blackPegs (cons 1 blackPegs))

或者在最后添加一个新元素:

(set! blackPegs (append blackPegs (list 1)))

但是,请注意,在 Scheme 中不建议使用这种编程风格,您应该尽量避免变异变量 - 首选函数式编程风格。

于 2013-03-21T02:43:17.560 回答