我正在尝试使用 Racket 为 BlackJack 游戏制作一整副扑克牌。但是,我有两个问题:
当我使用以下代码时
;This function creates a list of all the card faces.
(define faces '(2 3 4 5 6 7 8 9 10 J Q K A))
;This function creates a list of all card suits.
(define suits '(Clubs Diamonds Hearts Spades))
;make-deck: Creates a new (unshuffled) 52 card deck
; Returns: The deck (a list of cards)
; Parameters: none
(define make-deck
(letrec ([pair-items (lambda (x y)
(cond
[(null? x) '()]
[(null? y) '()]
[(displayln (cons (car x) (cons (car y) (pair-items x (cdr y)))))]
))])
(pair-items faces suits))
)
我明白了
(2 Spades)
(2 Hearts . #<void>)
(2 Diamonds . #<void>)
(2 Clubs . #<void>)
我不知道问题是什么。
我不知道如何重置
iterator
以将 faces
函数中的下一个元素与整个 suits
函数配对。我用let
吗?
cartesian-product
生成卡片列表(您还可以使用 for*/list
迭代 faces
和 suits
列表以获得相同的效果)。两者均如下所示:
#lang racket/base
(require racket/list)
;This function creates a list of all the card faces.
(define faces '(2 3 4 5 6 7 8 9 10 J Q K A))
;This function creates a list of all card suits.
(define suits '(Clubs Diamonds Hearts Spades))
; These two variables should be equal?
(define deck-1 (cartesian-product faces suits))
(define deck-2 (for*/list ([face (in-list faces)]
[suit (in-list suits)])
(list face suit)))
您的代码的一个大问题是使用
(cond ... [(displayln ...)])
。 displayln
始终返回一个 void 值,由于它不是 #f
,因此在 cond
中始终算作 true。如果没有 cond-clause 的 test-body 部分,真正的 test-expr 返回的是 cond
的计算结果,所以这就是您要添加到函数正在打印的列表中的内容(但不返回)。您可能应该首先将数据的“显示”与“创建”分开。