我有以下代码,它实现了筛子或Eratosthenes:
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行遇到了一个解析错误,“可能是错误的缩进或括号不匹配”。
这是为什么?
答案 0 :(得分:2)
我相信你想用{x}来写// Getting the absolute root path
define('ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR);
include_once("App/Core/Config/config.php");
include_once(CORE_PATH . DIRECTORY_SEPARATOR . "Include/autoloader.php");
//echo ('location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . "?comp=login_controller/noAuth");
if (!isset($_GET['comp']))
{
header('location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . "?comp=login_controller/noAuth");
}
$app = new Application();
$app->run();
。您可以在filter
之后添加do
。但是,这段代码是纯粹的(即非monadic),我会推荐这种语法:
filter ls indx =
...但是您的代码给了我以下错误:
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
答案 1 :(得分: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上找到有关缩进的更多信息,其中包含有关此类错误的一些很好的可视化示例。