haskell,计算列表中有多少素数

sef*_*osu 3 primes haskell function list

ima新手到haskell,目前我需要一个函数'f',给定两个整数,返回它们之间的素数的数量(即,大于第一个整数但小于第二个整数).

Main>  f 2 4
1
Main> f 2 10
3
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止的代码,但它起作用了.有什么建议?谢谢..

f :: Int -> Int -> Int
f x y 
  | x < y = length [ n | n <- [x..y], y 'mod' n == 0] 
  | otherwise = 0
Run Code Online (Sandbox Code Playgroud)

Fre*_*Foo 6

  • 从您的示例来看,您需要打开间隔(x,y)中的素数数量,在Haskell中表示[x+1 .. y-1].
  • 你的素性测试是有缺陷的; 你正在测试的因素y.
  • 要将函数名称用作中缀运算符,请使用反引号(`),而不是单引号(').

试试这个:

-- note: no need for the otherwise, since [x..y] == [] if x>y
nPrimes a b  =  length $ filter isPrime [a+1 .. b-1]
Run Code Online (Sandbox Code Playgroud)

为读者练习:实施isPrime.请注意,它只需要一个参数.