【问题标题】:Minimax operations on nested lists in Scheme/Racket/Lisp?Scheme / Racket / Lisp中嵌套列表的Minimax操作?
【发布时间】:2011-07-10 19:02:00
【问题描述】:

我正在尝试编写一个函数来分析游戏树。树由嵌套列表表示,其中每个子列表代表一个分支。基本上,我想弄清楚两件事:

  1. 嵌套列表的最小值是多少?
  2. 该值的索引是多少?

我以为我已经基本解决了第一个问题,但我的代码总是返回错误的值——我已经检查了所有内容,但看不到我做错了什么。

任何帮助将不胜感激,谢谢!

;MINIMAX*
(define minimax*
  (lambda (l operation hilo)
    (cond
      ((null? l) hilo)
      ((equal? operation 'max)
       (cond
         ((null? (cdr l)) (if
                           (list? (car l))
                           (minimax* (car l) 'min hilo)
                           (if
                            (> (car l) hilo)
                            (car l)
                            hilo)))
         (else (if
                (list? (car l))
                (if
                 (> (minimax* (car l) 'min hilo) hilo)
                 (minimax* (cdr l) 'max (minimax* (car l) 'min hilo))
                 (minimax* (cdr l) 'max hilo))
                (if
                 (> (car l) hilo)
                 (minimax* (cdr l) 'max (car l))
                 (minimax* (cdr l) 'max hilo))))))
      ((equal? operation 'min)
       (cond
         ((null? (cdr l)) (if
                           (list? (car l))
                           (minimax* (car l) 'max hilo)
                           (if
                            (< (car l) hilo)
                            (car l)
                            hilo)))
         (else (if
                (list? (car l))
                (if
                 (< (minimax* (car l) 'max hilo) hilo)
                 (minimax* (cdr l) 'min (minimax* (car l) 'max hilo))
                 (minimax* (cdr l) 'min hilo))
                (if
                 (< (car l) hilo)
                 (minimax* (cdr l) 'min (car l))
                 (minimax* (cdr l) 'min hilo))))))
      (else (error "Invalid operation type, must be 'max or 'min")))))

【问题讨论】:

  • 您首先可以做的一件事是简化代码。 Racket 中有 argminargmax 函数,它们返回列表的最小和最大元素,因此您不需要自己编写这些元素。还有minmax作为函数直接使用。如果您正在执行 minimax 算法而不是 alpha-beta 修剪,您可以使用递归 map 操作编写一个函数,这将更简单。
  • 或采用其他数据结构,如记录。
  • 如果您发布一些输入和预期输出值的示例,将会很有帮助。

标签: list search lisp scheme minimax


【解决方案1】:

你应该稍微改变你的方法。您可以实现一些实用程序,而不是编写一个基本程序来实现一切。

对于极小极大过程,数据来自树还是列表都没有关系。因此,您可以自己编写一个程序,将您的树转换为像这样的列表

 (define (fringe t)
   (cond ((null? t) t)
     ((pair? (car t)) (append (fringe (car t)) 
                      (fringe (cdr t))))
     (else (cons (car t) (fringe (cdr t))))))

检查最小值或最大值基本上是对列表或树的迭代。所以你可以用fold 做到这一点。见http://www.gnu.org/software/mit-scheme/documentation/mit-scheme-ref/Reduction-of-Lists.html

所以你可以这样写你的程序:

(define (minimax op t)
  (let ((flat-list (fringe t)))
    (fold op (car t) (cdr t))))

进一步阅读Structure and Interpretation of Computer Programs。这是一本学习方案和一般编程的好书。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-31
    • 2010-12-12
    • 2015-01-08
    • 2019-11-28
    • 2010-09-07
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多