返回int的打印函数

时间:2016-06-09 19:48:23

标签: haskell

在Haskell中,我正在尝试打印一个返回Int的方法。目前,mySum只是一个存根,因为我试图弄清楚如何打印它。

我查看了如何执行此操作,并且我看到putStr可以打印String并显示将Int转换为String所以我这样做了:

mySum :: [Int] -> Int
mySum _ = 0

main = putStr show mySum [1..5]

但是,我收到了这些错误:

Couldn't match expected type ‘([Int] -> Int) -> [Integer] -> t’
                with actual type ‘IO ()’
    Relevant bindings include main :: t (bound at weirdFold.hs:10:1)
    The function ‘putStr’ is applied to three arguments,
    but its type ‘String -> IO ()’ has only one
    In the expression: putStr show mySum [1 .. 5]
    In an equation for ‘main’: main = putStr show mySum [1 .. 5]

Couldn't match type ‘a0 -> String’ with ‘[Char]’
Expected type: String
  Actual type: a0 -> String
Probable cause: ‘show’ is applied to too few arguments
In the first argument of ‘putStr’, namely ‘show’
In the expression: putStr show mySum [1 .. 5]

那么如何实际打印方法的结果呢?

1 个答案:

答案 0 :(得分:14)

由于函数应用程序是左关联的,putStr show mySum [1..5]隐式括起来为((putStr show) mySum) [1..5]。有几种选择;一些列在下面。

  1. 明确括号:putStr (show (mySum [1..5]))
  2. 使用 - 关联函数应用程序运算符$;一个例子是putStr $ show (mySum [1..5])
  3. 将合成与$putStr . show . mySum $ [1..5]
  4. 一起使用
  5. 使用带括号的合成:(putStr . show . mySum) [1..5]