我相信你想写filter
与一个做记号。您只需在filter ls indx =
之后添加do
即可。但是,此代码是纯(即非一元),我会推荐这句法:
primeSieve :: Int -> [Int] -- Returns a list of primes up to upperbound
primeSieve upperbound = filter [2..upperbound]
where
filter ls indx =
let divisor = (ls!!indx)
filtered = [x | x <- ls, x `mod` divisor /= 0]
in if divisor*divisor >= last filtered
then filtered
else filter filtered (indx+1)
...但你的代码给了我以下错误:
<file>:13:25:
Couldn't match expected type `[Int]'
with actual type `Int -> [Int]'
Probable cause: `filter' is applied to too few arguments
In the expression: filter [2 .. upperbound]
In an equation for `primeSieve':
primeSieve upperbound
= filter [2 .. upperbound]
where
filter ls indx
= let ...
in
if divisor * divisor >= last filtered then
filtered
else
filter filtered (indx + 1)
Failed, modules loaded: none.
我觉得你的意思传递0
作为第二个参数filter
:
primeSieve :: Int -> [Int] -- Returns a list of primes up to upperbound
primeSieve upperbound = filter [2..upperbound]
where
filter ls indx =
let divisor = (ls!!indx)
filtered = [x | x <- ls, x `mod` divisor /= 0]
in if divisor*divisor >= last filtered
then filtered
else filter filtered (indx+1)
什么是“中如果”的意思? –
这只是一个'let ... in'子句,后跟一个'if'表达式。这里没什么魔法。 – baxbaxwalanuksiwe