Afflatus
Afflatus

Reputation: 943

Function Type in Haskell

I am new to Haskell. I want to have a function in which I get an Int value from the user using

putStr "Please Enter Your Number : "
submit_ans<- getLine

then after a series of calculations returns another Int which will be used by another function that has called it. What is the type of the described function? should I use return function at the end?

thanks in advance!

Update #1

ok I updated the function as below:

myFunction ::  Int -> IO Int 
myFunction action = do

      putStr "\tPlease Enter Your Number : "            
      submit_ans <- getLine 

      if action == 1
        then do 
       myFunctionII read submit_ans  
        else do
       putStrLn("\n")

it gives me this error:

*** Term           : myFunction 
*** Type           : Int -> IO Int
*** Does not match : IO a

Upvotes: 0

Views: 172

Answers (3)

Lee
Lee

Reputation: 144206

putStrLn has type String -> IO () and it seems myFunctionII has type Int -> IO (), so the type of myFunction should be Int -> IO () since both branches of your if return an IO ():

myFunction :: Int -> IO ()
myFunction action = do
  putStr "\tPlease Enter Your Number : "
  submit_ans <- getLine

  if action == 1
     then myFunctionII (read submit_ans)
     else putStrLn "\n"

Upvotes: 2

Will Ness
Will Ness

Reputation: 71119

Just write your function, say g, as a pure calculation, of type Int -> Int. Then you use it in IO monad as

...
putStr "Please Enter Your Number : "
submit_ans <- getLine
let i = g (read submit_ans)
...
print i

edit: Any Haskell value is pure. Functions are pure. IO x is a pure Haskell value. But it describes an impure computation, which will be run by the system (say, when your compiled application is run). As part of its execution, it will execute your pure function.

Upvotes: 2

Satvik
Satvik

Reputation: 11218

Since you are performing an IO operation and you are returning an Int so my best guess would be IO Int but I can't tell for sure because you question is too vague to answer clearly.

Upvotes: 1

Related Questions