简体   繁体   English

Haskell中的模式匹配错误

[英]Pattern matching error in haskell

Hello I have been attempting to answer a question that deals with checking if a number is a prime number. 您好,我一直在尝试回答一个有关检查数字是否为质数的问题。 I came up with this code below: 我想出了以下代码:

isitprime :: Int->Bool
isitprime n 
   | n<=1 = False
   | otherwise = isitprime2 n (n-1)

isitprime2 :: Int->Int->Bool
isitprime2 x y 
  | y > 1 && x `mod` y == 0 = False 
  | y == 1 && x `mod` y == 0 = True

When run in winhugs, it returns an error saying "pattern matching failure: isitprime2 a a-1 " for any value greater than 2. 当在winhugs中运行时,对于任何大于2的值,它都会返回一条错误消息“模式匹配失败:isitprime2 a a-1”。

However it returns false for any values which are directly multiplied by 2, eg isitprime2 2 1 returns false, isitprime2 4 2, isitprime2 6 3, isitprime2 10 5 etc. all return false. 但是,对于直接乘以2的任何值,它返回false,例如isitprime2 2 1返回false,isitprime2 4 2,isitprime2 6 3,isitprime2 10 5等。都返回false。

What is going wrong and why? 怎么了,为什么?

Thanks :D 感谢:D

The problem with the function isitprime2 is that it doesn't handle all cases. 函数isitprime2的问题在于它不能处理所有情况。 Like what happens when: 就像在以下情况下会发生什么:

  • y > 1 && x mod y != 0
  • y == 1 && x mod y != 0

Handle other cases and your code will work fine. 处理其他情况,您的代码将正常工作。 You can also use otherwise clause for handling all the edge case: 您还可以使用otherwise子句来处理所有边缘情况:

isitprime2 :: Int->Int->Bool
isitprime2 x y 
  | y > 1 && x `mod` y == 0 = False 
  | y == 1 && x `mod` y == 0 = True
  | otherwise = ??? -- handle all edge case

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM