球拍 - 从列表中挑选一个随机元素

时间:2015-11-20 04:26:46

标签: functional-programming racket

我不确定如何使这段代码正常工作,它在这里已经很晚了,我认为我的大脑已经停止运作,有人愿意帮助我吗?

到目前为止的代码:

(define maze-size 15)
(define-struct Cell (x y))

; adjacents : Cell -> list-of-Cells
; Produce a list of the four Cells above, below, left, and right of 'cell'.

(define(adjacents cell x y)
(list
(make-Cell x (+ y 1))
(make-Cell x (- y 1))
(make-Cell (- x 1) y)
(make-Cell (+ x 1) y)))

这里是我难倒的地方,我该如何解决这个问题? 注意:以下代码不起作用。

; random-adjacent : list-of-Cells -> Cell
; Produce a random Cell adjacent to a random Cell from the non-empty list'cells'.

(define (random-adjacent cells)
(random (adjacents cell)))

这就是它的行为:

(check-expect (member? (random-adjacent (list (make-Cell 123 104)))
                   (list (make-Cell 123 105)
                         (make-Cell 123 103)
                         (make-Cell 122 104)
                         (make-Cell 124 104)))
          #true)

1 个答案:

答案 0 :(得分:1)

这通过了你的测试:

 
(define-struct Cell (x y))

(define (adjacents cell)
  (list
   (make-Cell (Cell-x cell) (+ (Cell-y cell) 1))
   (make-Cell (Cell-x cell) (- (Cell-y cell) 1))
   (make-Cell (- (Cell-x cell) 1) (Cell-y cell))
   (make-Cell (+ (Cell-x cell) 1) (Cell-y cell))))

(define (random-adjacent cell)
  (let ((neighbors (adjacents cell)))
    (list-ref neighbors (random (length neighbors)))))

(check-expect (member? (random-adjacent (make-Cell 123 104))
                       (list (make-Cell 123 105)
                             (make-Cell 123 103)
                             (make-Cell 122 104)
                             (make-Cell 124 104)))
              #true)