2016-08-21 56 views
0

我有以下代码,它实现了筛或埃拉托塞尼:Haskell中:解析错误在嵌套where子句

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) 

我获得第4行,“不正确可能压痕或不匹配的括号”解析错误。

这是为什么?

回答

1

的问题是filter的定义比它建议立即进行删除是什么小的压痕。最重要的部分是

where filter ls indx = 
    let divisor = (ls!!indx) 

其中let开始的filter上面的行之前的4个字符。这会触发语法错误。要解决它,你可以缩进更多filter定义

where filter ls indx = 
     let divisor = (ls!!indx) 

更常见的格式是

where 
    filter ls indx = 
    let divisor = (ls!!indx) 

因为这样你不缩进太多。

您可以找到有关在haskell wiki压痕其中包含有关这种错误的一些不错的视觉示例的详细信息。

2

我相信你想写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) 
+0

什么是“中如果”的意思? –

+1

这只是一个'let ... in'子句,后跟一个'if'表达式。这里没什么魔法。 – baxbaxwalanuksiwe