A Haskell function of type: IO String-> String

ChrisQuignon picture ChrisQuignon · Nov 4, 2009 · Viewed 29.8k times · Source

I wrote a bunch of code in Haskell to create an index of a text. The top function looks like this:

index :: String -> [(String, [Integer])]
index a = [...]

Now I want to give this function a String read from a file:

index readFile "input.txt"

Which won't work because readFile is of type FilePath -> IO String.

Couldn't match expected type 'String' against inferred type 'IO String'

I see the error, but I can't find any function with type:

IO String -> String

I guess the key to success lies somewhere under some Monads, but I could not find a way to solve my problem.

Answer

cthulahoops picture cthulahoops · Nov 4, 2009

You can easily enough write a function that calls the readFile action, and passes the result to your index function.

readAndIndex fileName = do
    text <- readFile fileName
    return $ index text

However, the IO monad taints everything that uses it, so this function has the type:

readAndIndex :: FilePath -> IO [(String, [Integer])]