如何在Haskell中创建函数minimax?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Haskell中创建函数minimax?相关的知识,希望对你有一定的参考价值。
我一直在努力在Haskell中创建一个minimax函数,并且在SO上找不到任何好的替代品,因此我要问:
我想创建以下功能:
minimax :: Player -> Rose Board -> Rose Int
我想得到一个RoseTree of Integers,那些必须是1,0或-1(对于有转弯的玩家来说,移动可以是好的,中立的或坏的。
(root :> leaves) -- constructor of a Rose
(board :> boards) -- constructor of a Rose Board
(Int :> Ints) -- constructor of a Rose Int
我已经编写了函数hasWinner,minimal'和maximum'来简化:
hasWinner :: Board -> Maybe Player
minimum' :: [Int] -> Int
minimum' (x:xs) | x == -1 = -1
| otherwise = minimum' xs
maximum' :: [Int] -> Int
maximum' (x:xs) | x == 1 = 1
| otherwise = maximum' xs
此外,我认为我的基本情况如下:
minimax player (board :> []) = (0 :> [])
目前这就是我所在的地方:
minimax player (board :> boards)| maximum' [(isWinner player b (minimax' player)) | (b :> bs) <- boards] == 1 = _
| minimum' [(isWinner player b (minimax' player)) | (b :> bs) <- boards] == -1 = _
| otherwise = _
where minimax' player | player == P1 = P2
| otherwise = P1
isWinner p1 board p2 | hasWinner board == Just p1 = 1
| hasWinner board == Just p2 = -1
| otherwise = 0
我似乎无法弄清楚当我找到一块既赢,丢失或没有后果的董事会时会发生什么。那么我如何使用正确的Rose Board再次调用minimax函数?
任何帮助是极大的赞赏!
拉蒙
答案
我实际上发现了另一篇文章,讨论了我在这里遇到的同样问题:Haskell Recursive Minimax Tree
答案如下:
minimax :: Player -> Rose Board -> Rose Int
minimax p (r :> []) | hasWinner r == Just P1 = 1 :> []
| hasWinner r == Just P2 = (-1) :> []
| otherwise = 0 :> []
minimax P1 (r :> rs) = maximum (map root xs) :> xs
where xs = map (minimax (nextPlayer P1)) rs
minimax P2 (r :> rs) = minimum (map root xs) :> xs
where xs = map (minimax (nextPlayer P2)) rs
我希望至少这可以在将来帮助其他人。这个答案中使用的函数是:
root :: Rose a -> a
root (a :> bs) = a
nextPlayer :: Player -> Player
nextPlayer P1 = P2
nextPlayer P2 = P1
hasWinner :: Board -> Maybe Player
minimum :: Ord a => [a] -> a
maximum :: Ord a => [a] -> a
干杯!
以上是关于如何在Haskell中创建函数minimax?的主要内容,如果未能解决你的问题,请参考以下文章