Dusan Kolar wrote:
>
> Hi,
>
> Could anyone, please, give me reference to or a sophisticated
> answer?
>
> I am going to have maybe a very stupid question.
> Playing with IO monads I made to me a task. Create
> a function which counts lines of a file and returns the
> number of lines as a result:
>
> lineNo :: String -> Int
> fname number of lines
>
> To access files I'm using standard file access and operators
> defined in class Monad. The problem is, that when I count
> the lines, I'm imprisoned by IO monad. Is there any way
> (e.g. by converting value to String and obtaining this string as a result)
> how to break IO monads?
Monads do indeed have a viral nature to them. That is, once you use a
monadic function, you are required to make the calling function monadic,
and it's calling function, and it's calling function, and it's...
The trick to using monads is figuring out the best way to quarantine
them. In your example, the best strategy would be to have a [pure]
function that counts the number of lines in a string, another [monadic]
function that returns the contents of a file as a string, and a third
function that joins the two:
> countLines :: String -> Int
> readFile :: String -> IO String
> main = do
> fileContents <- readFile "foo.txt"
> print (countLines fileContents)
- Michael Hobbs