Home > Software design >  Haskell: Parse error in pattern: a - 1 Possibly caused by a missing 'do'?
Haskell: Parse error in pattern: a - 1 Possibly caused by a missing 'do'?

Time:06-22

While trying to implement the famous Ackermann function in Haskell to test whether the promised difference in running time is actually measurable, I stumbled across this beauty of an error description:

   Parse error in pattern: a - 1 
   Possibly caused by a missing 'do'?

I know that this parsing error is appearing pretty commonly and I have no idea why it does so. Other than that, my code (see below) should be fine.

My code:

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

CodePudding user response:

Don't use do and return for ak. do blocks are used for monadic computations. You can work with:

ak 0 b = b   1
ak a 0 = ak (a-1) 1
ak a b = ak (a-1) (ak a (b-1))

Then you can implement main as:

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))
  • Related