Here is my function:
foo :: Int -> Int
foo i = do
putStrLn "Foo Function has run!"
return (i*2)
The above has a compile time error.
I want it to be the case that if I did this:
bar = foo 6
bar would be 12.
but when the function is first run, it prints out the string "Foo Function has run!" How can i do this?
You have to make the function into an IO action. Haskell strictly enforces that you separate code that does IO from code that doesn't:
foo :: Int -> IO Int
foo i = do
putStrLn "Foo Function has run!"
return (i * 2)
You could then extract this value inside another IO
function:
main :: IO ()
main = do
bar1 <- foo 6
bar2 <- foo bar1
print (bar1, bar2)
The reasons why Haskell chooses this route are many and varied, but some of the important ones (in no particular order) are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With