如果Haskell中的数字是素数或不是素数,则要打印的函数中存在错误
我是Haskell的初学者,我决定尝试编写一个简单的函数来检查一个数字是否为素数。这是我的尝试。如果它太破旧,请原谅我如果Haskell中的数字是素数或不是素数,则要打印的函数中存在错误,haskell,Haskell,我是Haskell的初学者,我决定尝试编写一个简单的函数来检查一个数字是否为素数。这是我的尝试。如果它太破旧,请原谅我 isPrime x = if x > 2 then (True `elem` [(x `mod` num)==0 |num<-[2..x/2]]) else if x>0 then True else False 使用interactive GHC,我在iPrime 7中键入时的错误如下: <interactive>:75:1: error:
isPrime x = if x > 2 then (True `elem` [(x `mod` num)==0 |num<-[2..x/2]]) else if x>0 then True else False
使用interactive GHC,我在iPrime 7中键入时的错误如下:
<interactive>:75:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘isPrime’
prevents the constraint ‘(Integral a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Integral Integer -- Defined in ‘GHC.Real’
instance Integral Int -- Defined in ‘GHC.Real’
instance Integral Word -- Defined in ‘GHC.Real’
• In the expression: isPrime 7
In an equation for ‘it’: it = isPrime 7
<interactive>:75:9: error:
• Ambiguous type variable ‘a0’ arising from the literal ‘7’
prevents the constraint ‘(Num a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Double -- Defined in ‘GHC.Float’
instance Num Float -- Defined in ‘GHC.Float’
...plus two others
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the first argument of ‘isPrime’, namely ‘7’
In the expression: isPrime 7
In an equation for ‘it’: it = isPrime 7
以下是您的代码的错误: mod要求所涉及的数字是整数的实例 /要求所涉及的数字是分数浮点的实例 因此,x必须是整数和分数,这在Haskell标准库中是不存在的。相反,您可以使用div,它类似于/但对Integral进行操作: isPrime x=如果x>2,则为True`elem`[x`mod`num==0 | num0,则为True,否则为False 但是,您的代码也有逻辑错误,并且比可能的要长得多。首先,您不是在数组中查找True,而是在数组中查找不存在的True,因此您必须否定该语句。此外,您可以使用函数保护: iPrime::积分a=>a->Bool 互质x |x>2=all\num->x`mod`num/=0[2..x`div`2] |否则=x>1
以下是您的代码的错误: mod要求所涉及的数字是整数的实例 /要求所涉及的数字是分数浮点的实例 因此,x必须是整数和分数,这在Haskell标准库中不存在。相反,您可以使用div,它类似于/但对整数进行操作: isPrime x=如果x>2,则为True`elem`[x`mod`num==0 | num0,则为True,否则为False 但是,您的代码也有逻辑错误,并且比可能的要长得多。首先,您不是在数组中查找True,而是在数组中查找不存在的True,因此您必须否定该语句。此外,您可以使用函数保护: iPrime::积分a=>a->Bool 互质x |x>2=all\num->x`mod`num/=0[2..x`div`2] |否则=x>1
次要样式注释:不要编写True`elem`list,使用或list,同时查找任何和,所有这些都是相当常见的。此外,如果是cond,那么True else False要编写cond还有很长的路要走。if…那么…else x>0没有错:这里x>0已经是您需要的布尔值,因此不需要在上面使用if。次要样式注释:不要写True`elem`list,使用或list,同时查找任何和,所有这些都是相当常见的。此外,如果cond那么True或者False写cond是一个很长的过程。if…那么…else x>0没有什么问题:这里x>0已经是您需要的布尔值,所以不需要在上面使用if。