This topic is now archived and is closed to further replies.

Haskell Question

This topic is 5041 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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]

Share this post

Link to post
Share on other sites
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 ] -> [ b ]

bar :: IO [ a ] -> IO [ b ]
bar ios = do { str <- ios; return $ foo str }

return here brings a primitive value (foo str) into the IO monad.

This can also be written as

bar ios = ios >>= (\str -> return $ foo str)

This way of writing may more clearly give the idea.
(\str -> return $foo str) 
is a function of type
Monad m => [ a ] -> m [ b ] 
. The binding operator (
) provides a way of using the value of this monad together with this function to yield a new monad.

It's hard to explain because this concept has so much generality. It's not necessarily performing the computations in sequence, only the IO and State monads do that. The List monad, for instance, performs the function on 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 on the data.

[edited by - Flarelocke on February 21, 2004 6:44:05 PM]

Share this post

Link to post
Share on other sites