Append to List Variable with Racket
append, list, racket, scheme
Solution
If you want to modify (using `set!`) a list that already exists, do something along these lines, for adding a new element at the beginning:
(set! blackPegs (cons 1 blackPegs))
Or for adding a new element at the end:
(set! blackPegs (append blackPegs (list 1)))
However, be warned that in Scheme this style of programming is not recommended, you should try to avoid mutating variables - a functional programming style is preferred.
Problem
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.