2016-06-09 83 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