bsky
bsky

Reputation: 20242

Print function that returns int

In Haskell, I am trying to print a method which returns an Int. For now, mySum is just a stub because I'm trying to figure out how to print it.

I looked up how to do this and I saw putStr can print a String and show converts an Int to a String so I did this:

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

main = putStr show mySum [1..5]

However, I am getting these errors:

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]

and

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]

So how can I actually print the result of the method?

Upvotes: 1

Views: 3821

Answers (1)

chepner
chepner

Reputation: 532268

Because function application is left-associative, putStr show mySum [1..5] is implicitly parenthesized as ((putStr show) mySum) [1..5]. There are a few options; some are listed below.

  1. Parenthesize explicitly: putStr (show (mySum [1..5]))
  2. Use the right-associative function application operator $; one example is putStr $ show (mySum [1..5])
  3. Use composition with $: putStr . show . mySum $ [1..5]
  4. Use composition with parentheses: (putStr . show . mySum) [1..5]

Upvotes: 14

Related Questions