【问题标题】:Haskell type cast problemHaskell 类型转换问题
【发布时间】:2010-12-29 23:02:39
【问题描述】:

示例代码:

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

main = do
        putStrLn show fac 10

错误:

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

【问题讨论】:

    标签: haskell casting types


    【解决方案1】:

    让我们添加括号来说明这段代码是如何被实际解析的:

    (((putStrLn show) fac) 10)
    

    您将show 作为putStrLn 的参数,这是错误的,因为show 是一个函数,而putStrLn 需要一个字符串。你希望它是这样的:

    putStrLn (show (fac 10))
    

    您可以像这样给它加上括号,也可以使用$ 运算符,它基本上将它右边的所有内容都加上括号:

    putStrLn $ show $ fac 10
    

    【讨论】:

    • ($) 和 (.) 是你的挚友
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 2012-10-01
    相关资源
    最近更新 更多