[Haskell-cafe] How to convert from "IO String" to String

Dmitri Pissarenko mailing-lists at dapissarenko.com
Tue Jan 25 13:48:42 EST 2005


I have a function, which reads the contents of a file into a string:

readImage :: String -> IO String
readImage filename = do
	fileContent <- readFile filename
	return fileContent

The result of this function is fed into another function, which converts the
string content of the file (it is a PGM image file) into a list of integer
values (one integer for each pixel, one-dimensional array):

convertToList fileContent = drop 3 fileContentNumbers
	where 	fileContentNoComments = removeComments fileContent
		fileContentTokens = words fileContentNoComments
	      	fileContentNumbers = map read (tail fileContentTokens)
		fileContentNumArr = listArray (1, length fileContentNumbers)

Then, I wanted to verify that this function works properly and wrote a test
case, which reads an image and tests whether the resulting list is correct:

testConvertToList01 = TestCase (assertEqual "" [0, 255, 255, 255, 255, 0, 255,
255, 255, 255, 0, 255, 255, 255, 255, 0] (convertToList (readImage "../data-

When I load the files (you will find them all in attachment) into GHCi, I get
following error

    Couldn't match `String' against `IO String'
        Expected type: String
        Inferred type: IO String
    In the application `readImage "../data-test/diagonalImage.pgm"'
    In the first argument of `convertToList', namely
        `(readImage "../data-test/diagonalImage.pgm")'

I suppose that the error is due to this call in the test case:

(convertToList (readImage "../data-test/diagonalImage.pgm"))

readImage returns IO String and convertToList accepts String.

How can I re-write this test case so that it works?

Thanks in advance

Dmitri Pissarenko
Dmitri Pissarenko
Software Engineer
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Lik.hs
Type: text/x-haskell
Size: 1329 bytes
Desc: not available
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20050125/8795fde9/Lik.bin
-------------- next part --------------
A non-text attachment was scrubbed...
Name: TestLik.hs
Type: text/x-haskell
Size: 542 bytes
Desc: not available
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20050125/8795fde9/TestLik.bin

More information about the Haskell-Cafe mailing list