Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 这个功能,用来确定石头剪纸的结果,对吗?_Haskell - Fatal编程技术网

Haskell 这个功能,用来确定石头剪纸的结果,对吗?

Haskell 这个功能,用来确定石头剪纸的结果,对吗?,haskell,Haskell,我想做一个函数,告诉你一个石头剪刀游戏的结果,给定两个输入: 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 beats move = cas

我想做一个函数,告诉你一个石头剪刀游戏的结果,给定两个输入:

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
beats move = case move of
    Paper    -> Scissors
    Rock     -> Paper
    Scissors -> Rock

loses :: Move -> Move
loses move = case move of
    Scissors -> Paper
    Paper -> Rock
    Rock -> Scissors

-- find out what the score is for moves and return Win or Draw or Lose
score :: Move -> Move -> Result
score this_move opposing_move = case this_move of
    opposing_move -> Draw
    beats opposing_move -> Win
    loses opposing_move -> Lose
它返回错误消息:

parse error on input ‘=’

这意味着我在代码中写的一个等号有问题,对吗?不过,我看不出等号组合有任何问题。

正如卡斯滕指出的,模式匹配要简单得多;你甚至不需要中间函数

score :: Move -> Move -> Result
score Paper Rock = Win  -- paper beats rock
score Rock Scissors = Win -- rock beats scissors
score Scissors Paper = Win -- scissors beats paper
score x y | x == y = Draw  -- same move is a draw
score _ _ = Lose -- anything else is a loss

这是一个非常接近你的版本

-- 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

loses_to :: Move -> Move -> Bool
loses_to = flip beats

-- 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

你对
案件的识别对我来说很糟糕,它们应该是case中的pass che
c
这是在
丢失的情况下
-您使用的是
=
而不是
->
-只是比较一下其他的-我找不到常见的选项卡问题-score
功能可能也会导致一些问题-最好使用guardsbtw:您根本不需要
case
如果你只是使用模式匹配:
loss Scissor=Paper
等等。逻辑本身似乎很好,甚至是很好的/可读的风格-只要纠正一个语法问题,你应该很好地去做。你不能
case这个动作是另一个动作的动作->…
并期望检查是否相等。而是将
其他移动
变量重新绑定到
此移动
的值。使用
-Wall
启用警告将发现此错误(“重叠模式”)。您的意思是改为写“|beats this_move against_move=Win”吗?beat是一个函数,所以应该在末尾使用参数吗?如果你使用backticks
a`f`b
-它与
fab
相同-但是它读起来更好-这就是为什么我在这里也颠倒了情况-你需要函数返回a
Bool
来充当守卫
loss_to=flip beats
@amalloy很好的一点-事实上我忘记了最后一个案例<代码>输给<代码>无论如何…)