Haskell,不知道为什么输入'if'*上有*解析错误

时间:2014-11-12 06:50:37

标签: haskell functional-programming

这是取一个数字,得到它的阶乘并加倍它,但是由于基本情况如果你输入0它给2作为答案所以为了绕过它我使用了if语句,但是得到错误 解析输入'if'时出错。如果你们能提供帮助,真的很感激:)

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

1 个答案:

答案 0 :(得分:5)

我发现了两个问题 应该解决

  1. 您的let没有延续: (else let y = doub (fact num) ...)。 由于您不在do内,因此您可能希望将其更改为let ... in声明。
  2. 您的if缩进太远。它应位于let下。
  3. 我已经纠正了我提到的内容,代码对我有用......

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