簡體   English   中英

Haskell-遞歸

[英]Haskell - Recursion

我正在嘗試制作一個紙牌游戲,其中有兩個玩家在其中顯示紙牌,而排名最高的那個人則贏得並拿到了紙牌。(戰爭紙牌游戲) 我遇到的麻煩是整個游戲的運行,以查看獲勝者的最終結果。 我編寫了可以完成一輪游戲的代碼:

type ComparisonRule = Card -> Card -> Bool
type RoundRule = ([Card],[Card]) -> ([Card],[Card])

standardComparison :: ComparisonRule
standardComparison (Card r1 _) (Card r2 _)
    | r1 > r2  = True
    |otherwise = False

roundWithoutWar :: ComparisonRule -> RoundRule
roundWithoutWar f (x:xs,y:ys)
        |f x y     = (xs ++ [x] ++ [y],ys)
        |f y x     = (xs,ys ++ [y] ++ [x])
        |otherwise = (xs,ys)

我用

standardRound :: RoundRule
standardRound =  roundWithoutWar standardComparison
to run one round of the game.

我正在嘗試制作一個完整的游戲功能,該功能可以遞歸運行直到有人獲勝(獲勝者是擁有最多紙牌的人):

fullGame :: RoundRule -> ([Card],[Card]) -> [([Card],[Card])]
fullGame r  ([],[]) = [([],[])]
fullGame r ([],y:ys)        = [([],y:ys)]
fullGame r (x:xs,[])      = [(x:xs,[])]
fullGame r (x:xs,y:ys)       = (x:xs,y:ys) : fullGame ( r (x:xs,y:ys))

“ r”是單回合函數(StandardRound)但是,當我嘗試運行完整的游戲功能時出現錯誤

 War_Project_2.hs:138:46:
    Couldn't match expected type ‘[([Card], [Card])]’
                with actual type ‘([Card], [Card]) -> [([Card], [Card])]’
    Probable cause: ‘fullGame’ is applied to too few arguments
    In the second argument of ‘(:)’, namely
      ‘fullGame (r (x : xs, y : ys))’
    In the expression: (x : xs, y : ys) : fullGame (r (x : xs, y : ys))

War_Project_2.hs:138:57:
    Couldn't match type ‘([Card], [Card])’
                   with ‘([Card], [Card]) -> ([Card], [Card])’

    Expected type: RoundRule
      Actual type: ([Card], [Card])
    Possible cause: ‘r’ is applied to too many arguments
    In the first argument of ‘fullGame’, namely ‘(r (x : xs, y : ys))’
    In the second argument of ‘(:)’, namely
      ‘fullGame (r (x : xs, y : ys))’

我試圖編寫以運行完整游戲的無積分功能是:

simpleFullGame ::([Card],[Card]) -> [([Card],[Card])]
simpleFullGame = fullGame simpleRound

有一個有用的功能幾乎可以完全滿足您的需求。

  iterate :: (a -> a) -> a -> [a]

這可以連續應用您的RoundRule函數,該函數本質上是一個更新函數。 您要做的就是在游戲完成后停止。

done :: ([Card],[Card]) -> Bool

然后,當您具有該功能時,您的整個游戲就會結束。

fullGame roundRule initState = takeWhile (not . done) (iterate roundRule initState)

由於Haskell是惰性的,因此不會在最終狀態以外的游戲狀態中生成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM