[Haskell-beginners] A basic misunderstanding of how to program with IO

Isaac Dupree ml at isaac.cedarswampstudios.org
Sun May 9 20:12:34 EDT 2010


On 05/09/10 19:30, Ken Overton wrote:
>
>> I think, yes your function looks close to typical Haskell, you're just
>> missing a "do", a pair of parentheses, and an "IO":
>
> Sorry, I'd definitely intended the 'do' to be there.
>
>>      interact :: String ->  IO Resp
>
> Thanks Isaac; so after I've called this how do I get the Resp value back out of the returned IO?

By using it in some other piece of IO.  For example,

main :: IO ()
main = do
   resp <- interact "hi there!"
   let modifiedResp = some function involving resp
   ...

You see, "IO" lets you distinguish between functions/values that require 
IO actions, and those that are completely pure (always give the same 
result, given the same arguments, as is typical in mathematics).  Just 
use your patience! : Every function that uses that resulting Resp will 
have to be in IO.  This is not as bad as it seems, because most of the 
processing of the Resp can be pure again: for example, the way you call 
parseResp which is a pure function, or "some function involving resp" in 
my example above.

i'd suggest

1. Practice. The typechecker will tell you when you get it wrong.

2. Generally try to mark less of your code as "IO", because this is good 
style ( -- it turns out to be easier to code [and refactor code] with 
pure functions, because you know they don't have side-effects, so you 
mostly don't need to worry about "when" or "how often" they're called.)

-Isaac


More information about the Beginners mailing list