Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output Integer to stdout in Haskell

Tags:

io

haskell

I have a simple function like:

nth :: Integer -> Integer

And I try to print it's result as follows:

main = do
    n <- getLine
    result <- nth (read n :: Integer)
    print result

The following error is generated:

Couldn't match expected type `IO t0' with actual type `Integer'
In the return type of a call of `nth'
In a stmt of a 'do' expression:
    result <- nth (read n :: Integer)

Also tried with putStrLn and a lot of other combinations with no luck.
I can't figure it out and I would need some help, being that I don't fully understand how stuff works around these IOs.

like image 645
Iulius Curt Avatar asked Apr 21 '12 23:04

Iulius Curt


People also ask

How do I print statements in Haskell?

If you have a String that you want to print to the screen, you should use putStrLn . If you have something other than a String that you want to print, you should use print . Look at the types! putStrLn :: String -> IO () and print :: Show a => a -> IO () .

What is >> in Haskell?

Essentially, a >> b can be read like "do a then do b , and return the result of b ". It's similar to the more common bind operator >>= .


2 Answers

nth is a function, not an IO action:

main = do
  n <- getLine
  let result = nth (read n :: Integer)
  print result
like image 129
Thomas M. DuBuisson Avatar answered Sep 28 '22 04:09

Thomas M. DuBuisson


The do syntax unwraps something within a monad. Everything on the right hand side of the arrow must live within the IO monad, otherwise the types don't check. An IO Integer would be fine in your program. do is syntactic sugar for the more explicit function which would be written as follows:

Recall that (>>=) :: m a -> (a -> m b) -> m b

main = getLine >>= (\x ->
       nth >>= (\y ->
       print y))

But nth is not a monadic value, so it doesn't make sense to apply the function (>>=), which requires something with the type IO a.

like image 36
rotskoff Avatar answered Sep 28 '22 05:09

rotskoff