2016-06-09 56 views
-3

在Haskell中,我试图打印一个返回Int的方法。目前,mySum只是一个存根,因为我试图找出如何打印它。返回int的打印函数

我抬起头来如何做到这一点,我看到putStr可以打印String并显示转换的IntString,所以我这样做:

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

尝试加入一些括号:'主要= putStr(显示(mySum [1..5]))'。功能应用程序是关联的。 – user2297560

+0

标题的第一印象:您正试图打印一个函数(而不是您在应用函数时获得的值)。你可以很容易地得出解决方案,意识到你只是想打印一个'Int'而不是一个函数。像'print n'('print = putStrLn。show'),然后替换'n':'print(mySum [1..5])'。为简单起见,我使用了'print',但您可以轻松使用'putStr。展示“或其他任何东西。 – jakubdaniel

回答

13

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

  1. 圆括号明确:putStr (show (mySum [1..5]))
  2. 使用权 -associative功能应用操作$;一个例子是putStr $ show (mySum [1..5])
  3. $使用组合物:putStr . show . mySum $ [1..5]
  4. 带括号使用组合物:(putStr . show . mySum) [1..5]
+1

这是所有伟大的建议(我upvoted答案),但我不得不问,为什么混合第二号答案....如果使用'($)',为什么不用'putStr $ show $ mySum [1..5]'? – jamshidh

+0

我在想'putStr $ show $ mySum $ [1..5]'(尽管最后一个实际上是不必要的),它一次会是太多的新运算符,因此仅限于使用它来替换一组括号。 – chepner