输入`='上的haskell解析错误也许你需要'do'块中的'let'?例如'让x = 5'而不是'x = 5'

时间:2018-04-19 19:46:57

标签: haskell

无法使我的haskell程序正常工作

sort [] = []
sort (x:xs) = sort [a | a <- xs , a<=x ] ++ [x] ++ sort [a | a <- xs , a > x]  

getList:: Int->[IO Int]  
getList 0 = [] --declaring the empty list
getList n = [a | a <- [getNumber] ] ++ getList (n-1)

getNumber::IO Int --get number function
getNumber = do
s <- getLine
return (read s)
--Main function to handle
main = do
p <- getNumber -- taking the number of variable
lst <- sequence (getList p) --calling gtlistFunction to input the list
print (sort lst) --print

错误:

quicksort.hs:13:6: error:
    parse error on input `='
    Perhaps you need a 'let' in a 'do' block?
    e.g. 'let x = 5' instead of 'x = 5'
   |
13 | main = do
   |      ^

2 个答案:

答案 0 :(得分:1)

您必须缩进所有do - 块:

-- NOT correct: this will fail
main = do
putStrLn "This is..."
putStrLn "WRONG!"

-- Correct:
main = do
  putStrLn "This is..."
  putStrLn "correct!"

只要一致,空格的数量并不重要。

为避免这种情况,你可以使用类似c的表示法:

-- Also correct:
main = do {
putStrLn "This is...";
putStrLn "also correct!";
}

这样你就可以自由缩进了。例如:

-- Also correct:
main = do
{ putStrLn "This is..."
; putStrLn "also correct!"
;}

答案 1 :(得分:0)

如果没有缩进,解析器不知道main = ...启动新定义,与前面的getNumber定义分开。以下工作正常:

getNumber::IO Int
getNumber = do
 s <- getLine
 return (read s)
main = do
p <- getNumber
lst <- sequence (getList p)
print (sort lst)

从一个空格缩进到无缩进的转换足以告诉解析器return (read s)是定义do的{​​{1}}块的最后一行,getNumber }是新的顶级定义的开始。

要么缩进代码,要么在AJFarmar的答案中使用显式括号语法,让解析器知道一个定义的结束位置和下一个定义的开始位置。