how to convert IO String to string---- still have questions
Nick Name
nick.name@inwind.it
Sun, 24 Nov 2002 20:14:04 +0100
On Sun, 24 Nov 2002 09:05:17 -0900
"Lu Mudong" <mudong@hotmail.com> wrote:
> Thanks a lot for you guys' help.
>
> I am very new to haskell and tried some methods you guys advised,
> doesn't seem to work, i think i didn't do it properly, here's my code
> and result, hope you can point out what's wrong. thanks!
>
> my code:
>
> myReadFile :: IO String
> myReadFile = readFile "d:/hugs98/input.txt"
>
> theString :: String
> theString = do
> s <- myReadFile
> putStrLn s
>
>
> the error message i got in hugs98
>
> ERROR "D:\hugs98\parser.hs":16 - Type error in explicitly typed
> binding*** Term : theString
> *** Type : IO ()
> *** Does not match : String
>
You can convert an IO string to a string, but the resulting string can
only be given as an input to a function of type
String -> IO <put your favourite type here>
This approach is called "monads" and is needed because haskell is a lazy
language, so order of evaluation is unspecified, while input/output
usually needs a precise order of evaluation. In fact the only way
(almost, but don't get confused by now) to execute non-purely-functional
code (i/o for example) in haskell is to bind the name "main" to an IO
operation.
Now consider your "theString" function: it executes myReadFile, which is
an IO operation, so theString is an IO operation itselv, and has type
"IO ()", since putStrLn has this type.
Note that I said "operation". If you think about types like "IO a" as
"An IO operation returning the type a" everything will be more clear.
Maybe someone has to suggest some simple article on monads.
Bye
Vincenzo