编程haskell代码:素数列表 [英] programming haskell code: List of primes
问题描述
我的任务是创建素数列表,但仅包含以下信息:
My task is to create a list of primes but only with the following information:
-列表必须是无限的
-我必须检查n > 1
的素数
-如果有一个变量2 <= k < n-2
将其除以n
,则它不是素数;如果它没有除以n
,则它为
-没有功能!
-The list has to be infinite
-I have to check up primes for n > 1
-If there is a variable 2 <= k < n-2
, which divides n
,then it is no prime, if it does not divide n
, it is
-No function!
所以我开始写这样的代码:
So I started writing a code like this:
primes = [n| n<-[2,3..],k<-[2,3..], if (k>=2) && (k<=(n-2))
then if n `mod` k /= 0 then n else return ()
else return () ]
但是随后出现以下错误:无法将期望的类型'Bool'与实际类型相匹配"
But then appears the following error : "Couldn't match expected type ‘Bool’ with actual type"
是因为return ()
,但是我不知道如何替换此return
.
It's because of the return ()
, but I don't know how to replace this return
.
我希望得到帮助.
推荐答案
假设您有一个函数:
isPrime :: Int -> Bool
返回素数为True,否则返回False.然后,您可以定义:
which returned True for primes and False otherwise. Then you could define:
primes = [ n | n <- [2..], isPrime n ]
使用功能all
,您可以这样编写isPrime
:
Using the function all
, you could write isPrime
like this:
isPrime n = all (\a -> mod n a /= 0) [2..n-1]
如果应用于xs
的每个成员的f
为True,则
all f xs
返回True.因此,如果对于[2..n-1]中的所有元素mod n a /= 0
,即不除n,则n
是素数.
all f xs
returns True if f
applied to every member of xs
is True. So n
is prime if for all elements in [2..n-1], mod n a /= 0
, i.e. a does not divide n.
all
函数的更多示例:
all even [2,4,10,12] -- True
all (\x -> x > 0) [4,-5,6] -- False
all (\xs -> length xs > 0) [ [3], [4,5], [-4] ] -- True
all (\x -> x*x < 0) [] -- True
您可以使用用于列表递归的标准模板自己定义all
:
You can come up with the definition of all
yourself by using the standard template for recursion on lists:
all f [] = ...
all f (x:xs) = ...
这篇关于编程haskell代码:素数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!