我一直在努力在Haskell中创建minimax函数,并且在SO上找不到任何出色的替代方案,因此我为什么要问:
我要创建以下功能:
minimax :: Player -> Rose Board -> Rose Int
我想获得一棵整数玫瑰树,它们必须为1、0或-1(对于有转牌的玩家来说,移动可以是好,中性或坏。
(root :> leaves) -- constructor of a Rose
(board :> boards) -- constructor of a Rose Board
(Int :> Ints) -- constructor of a Rose Int
我编写了hasWinner函数,“ minimum”和“ 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函数?
非常感谢您的帮助!
拉蒙
答案 0 :(得分:0)
我实际上发现了另一篇文章,讨论了我在这里遇到的相同问题: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
欢呼!