如何让try函数起作用?

时间:2015-11-20 09:19:07

标签: functional-programming racket

我希望我的函数(名为try)确保:

  1. 单元格不在单元格中

  2. 单元格的坐标介于0和迷宫大小1之间

  3. 细胞恰好接触细胞中的一个细胞。

  4. 解释

    (define maze-size 15)
    (define-struct Cell (x y))
    
    (define (random-element a-list)
    (list-ref a-list (random (length a-list))))
    
    (define (random-adjacent cell)
    (let ((neighbors (adjacents cell)))
    (list-ref neighbors (random (length neighbors)))))
    
    
    (define (count-in cell cells)
    (cond
    [(member? cell cells) 1]
    [else 0]))
    
    (define (touches cell cells)
    (+
    (count-in (make-Cell (Cell-x cell) (+ (Cell-y cell) 1)) cells)
    (count-in (make-Cell (Cell-x cell) (+ (Cell-y cell) -1)) cells)
    (count-in (make-Cell (+ (Cell-x cell) -1) (Cell-y cell)) cells)
    (count-in (make-Cell (+ (Cell-x cell) 1) (Cell-y cell)) cells)))
    

    以下是我的内容:

    (define (try cell cells)
    (cond [(=? 1(touches cell cells)) (member? cell cells) (=? 1(cell-post))]
    [(zero? (random (sqr maze-size))) cells]
    [else (extend cells)]))
    

    是的,我知道在第一个条件下语法是错误的,我的cond语句并不强大。

    在这种情况下需要什么语法?

    请记住,它也适用于此代码:

    (define (extend cells)
    (try (random-adjacent cells) cells))
    

1 个答案:

答案 0 :(得分:1)

未经测试,但您所描述的内容将表示为

 
(define (try cell cells)
  (and (not (member? cell cells))
       (<= 0 (Cell-x cell) maze-size)
       (<= 0 (Cell-y cell) maze-size)
       (= 1 (touches cell cells))))