所以我工作的一個極小實現了跳棋類遊戲,以幫助自己學習哈斯克爾更好。我遇到的功能需要列出遊戲狀態列表,並生成直接後繼遊戲狀態列表。就像跳棋一樣,如果有跳轉,球員必須拿下。如果有多個玩家可以選擇。簡化一些Haskell代碼
在大多數情況下,這個工程很好地與列表單子:遍歷所有輸入的遊戲狀態,遍歷可能再漲所有彈珠,環比那個大理石的所有跳躍。這個monad列表很好地將所有列表展平成最後的狀態列表。
訣竅是,如果沒有找到給定遊戲狀態的跳轉,我需要返回當前的遊戲狀態,而不是空的列表。下面的代碼是我想到的最好的方式,但對我來說似乎非常難看。有關如何清理它的任何建議?
eHex :: Coord -> Coord -- Returns the coordinates immediately to the east on the board
nwHex :: Coord -> Coord -- Returns the coordinates immediately to the northwest on the board
generateJumpsIter :: [ZertzState] -> [ZertzState]
generateJumpsIter states = do
ws <- states
case children ws of
[] -> return ws
[email protected]_ -> n
where
children [email protected](ZertzState s1 s2 b p) = do
(c, color) <- occupiedCoords ws
(start, end) <- [(eHex, wHex), (wHex, eHex), (swHex, neHex),
(neHex, swHex), (nwHex, seHex), (seHex, nwHex)]
if (hexOccupied b $ start c) && (hexOpen b $ end c)
then case p of
1 -> return $ ZertzState (scoreMarble s1 color) s2
(jumpMarble (start c) c (end c) b) p
(-1) -> return $ ZertzState s1 (scoreMarble s2 color)
(jumpMarble (start c) c (end c) b) p
else []
編輯:提供* Hex函數的示例類型簽名。
不能第一個列表理解只是[如果null(兒童ws)然後其他孩子ws | ws < - states]?我希望編譯器可以消除重複的函數調用。 – 2009-08-05 12:52:20
是的,編輯的代碼遵循您的評論 – 2009-08-05 14:47:08