Ashish Sondhi
Ashish Sondhi

Reputation: 31

Haskell, Don't know why this has a *parse error on input ‘if’*

This is to take a number, get its factorial and double it, however because of the base case if you input 0 it gives 2 as the answer so in order to bypass it i used an if statement, but get the error parse error on input ‘if’. Really appreciate if you guys could help :)

fact :: Int -> Int
fact 0 = 1
fact n = n * fact(n-1)

doub :: Int -> Int
doub r = 2 * r

factorialDouble :: IO()
factorialDouble = do 
                    putStr "Enter a Value: "
                    x <- getLine
                    let num = (read x) :: Int
                        if (num == 0) then error "factorial of zero is 0"
                            else let y = doub (fact num) 
                                    putStrLn ("the double of factorial of " ++ x ++ " is " ++ (show y))

Upvotes: 2

Views: 196

Answers (1)

Arnon
Arnon

Reputation: 2237

I've spotted two issues that should be addressed

  1. You have a let that has no continuation: (else let y = doub (fact num) ...). Because you're not inside a do, you would probably want to change it into a let ... in statement.
  2. Your if is indented too far in. It should be under the let.

I've corrected what I mentioned and the code works for me...

fact :: Int -> Int
fact 0 = 1
fact n = n * fact(n-1)

doub :: Int -> Int
doub r = 2 * r

factorialDouble :: IO ()
factorialDouble = do 
                    putStr "Enter a Value: "
                    x <- getLine
                    let num = (read x) :: Int
                    if num == 0 then (error "factorial of zero is 0")
                        else let y = doub (fact num) 
                        in putStrLn ("the double of factorial of " ++ x ++ " is " ++ (show y))

Upvotes: 5

Related Questions