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
表达式。这里没有什么神奇之处。