list - Scheme/Racket/Lisp 中嵌套列表的 Minimax 操作?

标签 list search lisp scheme minimax

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

  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")))))

最佳答案

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

对于 minimax 过程,数据是在树中还是列表中并不重要。所以你可以自己编写一个程序,将你的树转换成这样的列表

 (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 .这是一本学习 Scheme 和一般编程的好书。

关于list - Scheme/Racket/Lisp 中嵌套列表的 Minimax 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5227473/

相关文章:

java - List<String> @Test 从最后一个索引中删除 null

python - 对于 Python,如何对固定大小的列表中的元素进行排序和合并

performance - 搜索和排序立方体面积的算法

lisp - Common Lisp 中的替换

android - 列出Android手机下载目录下的文件

c# - 如何检索列表中下一个更高的数字?

elasticsearch - Elasticsearch查找距一组引用点最远距离的位置

c++ - 如何在二维 vector 中找到结构元素?

lisp - 从列表中删除元素

c - 是否有可能将类似 Lisp 的宏构建成命令式语言?