Haskell:嵌套where子句中的分析错误
我有以下代码,它实现了筛子或埃拉托斯烯:Haskell:嵌套where子句中的分析错误,haskell,Haskell,我有以下代码,它实现了筛子或埃拉托斯烯: primeSieve :: Int -> [Int] -- Returns a list of primes up to upperbound primeSieve upperbound = filter[2..upperbound] where filter ls indx = let divisor = (ls!!indx) let filtered = [x | x <- ls, x `mod` divisor
primeSieve :: Int -> [Int] -- Returns a list of primes up to upperbound
primeSieve upperbound = filter[2..upperbound]
where filter ls indx =
let divisor = (ls!!indx)
let filtered = [x | x <- ls, x `mod` divisor /= 0]
if divisor*divisor >= last filtered
then filtered
else filter filtered (indx+1)
primeSieve::Int->[Int]--返回一个到上限的素数列表
primeSieve上限=过滤器[2..上限]
其中,过滤器ls indx=
设除数=(ls!!indx)
设过滤=[x | x=上次过滤
然后过滤
else过滤器已过滤(indx+1)
我在第4行“可能不正确的缩进或不匹配的括号”中得到了一个解析错误
这是为什么?我相信您想用do符号编写
过滤器。您可以在过滤器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)
我相信您希望使用do符号编写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)
问题是filter
定义的缩进,它比应该的定义小。重要的部分是
where filter ls indx =
let divisor = (ls!!indx)
其中,let
在上面一行的过滤器
之前开始4个字符。这会触发语法错误。要修复它,您可以缩进更多的过滤器
定义
where filter ls indx =
let divisor = (ls!!indx)
更常见的格式是
where
filter ls indx =
let divisor = (ls!!indx)
因为这样你就不会缩进太多
您可以在上找到有关缩进的更多信息,其中包含有关此类错误的一些很好的视觉示例。问题是过滤器定义的缩进,它比应该的缩进小。重要的部分是
where filter ls indx =
let divisor = (ls!!indx)
其中,let
在上面一行的过滤器
之前开始4个字符。这会触发语法错误。要修复它,您可以缩进更多的过滤器
定义
where filter ls indx =
let divisor = (ls!!indx)
更常见的格式是
where
filter ls indx =
let divisor = (ls!!indx)
因为这样你就不会缩进太多
你可以在上面找到更多关于缩进的信息,缩进中包含了一些关于此类错误的很好的视觉示例。如果“in-if”是什么意思?这只是一个let…in
子句,后面跟着一个if
表达式。这里没有什么神奇的。如果“in-if”是什么意思这只是一个let…in
子句,后跟一个if
表达式。这里没有什么神奇之处。