Haskell Question

Started by
3 comments, last by CheeseMonger 20 years, 1 month ago
After reading in a string from a file, my function returns a IO [Char] type. How can I use this data with functions that require a [Char] or [ a ] ? For example, the display function returns a string read from the file:
MatIO> display
"SQ345 ","10","10","08","05","Manchester","Singapore"      
But if I try to reverse it:
MatIO> reverse display
ERROR - Type error in application
*** Expression     : reverse display
*** Term           : display
*** Type           : IO [Char]
*** Does not match : [ a ]  
How can I get around this issue? - CheeseMonger Edit: Bloody BB tags... [edited by - CheeseMonger on February 21, 2004 2:33:27 PM] [edited by - CheeseMonger on February 21, 2004 2:34:03 PM] [edited by - CheeseMonger on February 21, 2004 2:34:51 PM]
- CheeseMonger
Advertisement
You could try using (liftM reverse), to get a function of type IO [Char] -> IO [Char]. liftM is in the Monad module.
It gets rid of the error, but it doesn''t affect the string:

MatIO> liftM reverse display"SQ345 ","10","10","08","05","Manchester","Singapore" 


- CheeseMonger
- CheeseMonger
Instead of thinking about extracting the data from the IO monad, think of performing a computation within the monad, by binding the input of your new function to the input of the desired function.

foo :: [ a ] -> <br><br>bar :: IO [ a ] -> IO <br>bar ios = do { str <- ios; return $ foo str } </pre> <br><br>return here brings a primitive value (foo str) into the IO monad.<br><br>This can also be written as<pre><br>bar ios = ios >>= (\str -> return $ foo str) </pre> <br><br>This way of writing may more clearly give the idea.  <pre>(\str -> return $foo str) </pre>  is a function of type <pre>Monad m => [ a ] -> m  </pre> .  The binding operator (<pre>>>= </pre> ) provides a way of using the value of this monad together with this function to yield a new monad.<br><br>It's hard to explain because this concept has so much generality.  It's not necessarily performing the computations in sequence, &#111;nly the IO and State monads do that.  The List monad, for instance, performs the function &#111;n each of its members, and returns the concatenation of the results.  The Maybe monad returns Nothing if its input is Nothing, and ignores the function.  Otherwise it performs the function &#111;n the data.   <br><br><SPAN CLASS=editedby>[edited by - Flarelocke on February 21, 2004 6:44:05 PM]</SPAN>
---New infokeeps brain running;must gas up!
Cheers for the reply.

For other people that come across this ''feature'', I finally found a link that explains it in greater depth: http://www.haskell.org/hawiki/ThatAnnoyingIoType

- CheeseMonger
- CheeseMonger

This topic is closed to new replies.

Advertisement