[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


Hello!

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

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

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):

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

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:

<test-case>
testConvertToList01 = TestCase (assertEqual "" [0, 255, 255, 255, 255, 0, 255,
255, 255, 255, 0, 255, 255, 255, 255, 0] (convertToList (readImage "../data-
test/diagonalImage.pgm")))
</test-case>

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

<error-message>
    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")'
</error-message>

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
http://dapissarenko.com
-------------- 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