2

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))
3
  • 1
    Did you mix tabs and spaces? Commented Nov 12, 2014 at 6:54
  • The factorial of zero is 1 (you got this right in the definition of fact) which means that 2 is the correct answer. Commented Nov 12, 2014 at 9:33
  • @Franky The code uses tabs, but does not mix them with spaces (except for the initial 4 spaces for the SO code format) - you can check this in the edit form. Commented Nov 12, 2014 at 13:23

1 Answer 1

5

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))
Sign up to request clarification or add additional context in comments.

2 Comments

No in after the let?
On StackOverflow, be sure to mark the correct answer using the check mark next to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.