我对Haskell完全陌生(更广泛的是对函数式编程),所以如果这真的是基础知识,请原谅我。我正在阅读Real World Haskell,并且正在创建RPS游戏
data Move = Paper | Rock | Scissors
deriving (Eq, Show)
data Result = Win | Draw | Lose
deriving (Eq, Show)
-- function returns the move which beats the other move
beats :: Move -> Move -> Bool
beats Scissors Paper = True
beats Paper Rock = True
beats Rock Scissors = True
beats _ _ = False
-- instead I could use in the 2º line: loses_to = flip beats
loses_to :: Move -> Move -> Bool
loses_to Scissors Paper = False
loses_to Paper Rock = False
loses_to Rock Scissors = False
loses_to _ _ = True
-- find out what the score is for moves and return Win or Draw or Lose
score :: Move -> Move -> Result
score this_move opposing_move
| this_move `beats` opposing_move = Win
| this_move `loses_to` opposing_move = Lose
| otherwise = Draw
可能有很多更聪明的方法来创建此代码。但是在示例中,它使用了两个函数“ beats”和“ loses_to”。 我被困在创建一个称为赢家的函数中,如下所示: 称为“获胜者”的函数,它接收动作列表并返回获胜动作的索引列表。
winners :: [Move] -> ?
非常感谢您的帮助,
史蒂夫。