开发者

Haskell type cast problem

开发者 https://www.devze.com 2022-12-15 00:11 出处:网络
Example code: fac :: Int → Int fac 0 = 1 fac n = n * fac (n-1) main = do putStrLn show fac 10 Error: Couldnt match expected type \'String\'

Example code:

fac :: Int → Int
fac 0 = 1
fac n = n * fac (n-1)

main = do
        putStrLn show fac 10

Error:

Couldnt match expected type 'String'
       against inferred ty开发者_StackOverflowpe 'a -> String'
In the first argument of 'putStrLn', namely 'show'
In the expression: putStrLn show fac 10


Let's add parentheses to show how this code is actually parsed:

(((putStrLn show) fac) 10)

You're giving show as the argument to putStrLn, which is wrong because show is a function and putStrLn expects a String. You want it to be like this:

putStrLn (show (fac 10))

You could either parenthesize it like that, or you can use the $ operator, which essentially parenthesizes everything to the right of it:

putStrLn $ show $ fac 10
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号