非穷举模式匹配仅仅是因为我省略了`否则=`? [英] Non-exhaustive pattern matches only because I left off `otherwise =`?
本文介绍了非穷举模式匹配仅仅是因为我省略了`否则=`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用Haskell编写了一个简单的程序,播放the guessing game described in The Rust Programming Language book:
它的工作原理是这样的:程序将生成一个介于1和100之间的随机整数。然后,它会提示玩家输入一个猜测。输入猜测后,它将指示猜测是过低还是过高。如果猜测正确,游戏将打印祝贺并退出。
这是我写的:
import Control.Monad (when)
import System.Random (randomRIO)
-- | Check if the guess is correct, otherwise provide a hint
respond :: Int -> Int -> String
respond correct guess
| guess > correct = "Smaller than " ++ show guess
| guess < correct = "Larger than " ++ show guess
| guess == correct = "Correct! " ++ show correct
-- | Main game loop; prompt for input and repeat until guessed correctly
play :: Int -> IO ()
play x = do
putStr "Guess: "
guess <- read <$> getLine
putStrLn $ respond x guess
when (guess /= x) $ play x
-- | Start the game with a random number between 1 and 100
main :: IO ()
main = play =<< randomRIO (1, 100)
代码可以工作,但GHC给我一个警告"Pattern match(es) are non exhaustive. In an equation for 'respond': Patterns not matched: _ _"
respond
函数的参数的两个Ints
。我不明白的是我没有报道哪件案子。这些不是Maybe Int
或任何特殊的-因为函数需要两个有效的Ints
,所以我只需要处理整数-我认为没有任何数字不能被视为大于、小于或等于另一个数字?
这是否只是假设我没有覆盖所有案例,因为我没有添加最后的otherwise =
警卫?即使它在逻辑上涵盖了所有情况。
此外,如果您有任何关于如何编写更习惯的Haskell的提示,我将不胜感激。我还在学习基础知识。
推荐答案
GHC根本不知道a > b
、a < b
或a == b
中的一个必须计算为True
。(实际上,可以编写违反此假设的Ord
实例--尽管大多数程序员不会考虑这样做,而且Int
的实例肯定会在这方面表现良好。)
您可以通过使用完全模式匹配向GHC清楚地表明您已经覆盖了所有情况,例如
respond correct guess = case compare guess correct of
GT -> ...
LT -> ...
EQ -> ...
GHC在其警卫otherwise
和True
的穷举检查器中还有一个特殊情况,因此您可以使用此选项添加(或更换)其中一个警卫作为替代解决方案。
respond correct guess
| guess > correct = ...
| guess < correct = ...
| otherwise = ...
这篇关于非穷举模式匹配仅仅是因为我省略了`否则=`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文