在尝试在Haskell中实现著名的Ackermann函数以测试所承诺的运行时间差异是否实际上是可测量的时候,我偶然发现了这个美丽的错误描述:
Parse error in pattern: a - 1 Possibly caused by a missing 'do'?
我知道这个解析错误很常见,我不知道为什么会这样。除此之外,我的代码(见下文)应该没问题。
我代码:
main :: IO ()
main = do
print "Please enter first operand: "
input <- getLine
let n = read input
print "Please enter second operand: "
input <- getLine
let m = read input
let r = ak(n,m)
print(n++" ackermann "++m++" = "++show r)
ak(a,b) = do
if a == 0
then return (b+1)
else if b == 0
then return ak(a-1, 1)
else
s1 <- ak(a-1, b)
s2 <- ak(a-1, s1)
return s2
不要用do
和return
代替ak
。do
块用于一元计算。您可以使用:
ak 0 b = b + 1
ak a 0 = ak (a-1) 1
ak a b = ak (a-1) (ak a (b-1))
那么你可以实现main
为:
main :: IO ()
main = do
print "Please enter first operand: "
n <- readLn
print "Please enter second operand: "
m <- readLn
putStrLn (show n ++ " ackermann " ++ show m ++ " = " ++ show (ak n m))