[Haskell-cafe] Haskell File reading

Stefan O'Rear stefanor at cox.net
Tue Mar 6 23:48:29 EST 2007


On Wed, Mar 07, 2007 at 04:16:11AM +0000, cornmouse wrote:
> I have a txt file, which contains a paragraph. I am trying to read the file, 
> and pass the contents of the file as a string to another function 
> called "createIndex". "createIndex" is a function to generate index of the 
> input string.
> 
> Below is my code to read the file :
> 
> main :: IO ()
> main 
>      = do
>          putStr "Enter input file name.txt: "
>          filename <- getLine
>          content <- readFile filename
>          createIndex content
> 
> createIndex  ::  String  ->  [ ([Int], String) ]
> createIndex
>        {- contents of the function... -}
> 
> I am using Hugs compiler, when i execute, i got an error

One nitpick - Hugs isn't a compiler.  It is a pure interpreter, and a
relatively non-preferred one now, because it is much slower than ghci
for small programs, and has relatively less development effort.  (eg
the development version of ghci has a prototype debugger).

> Type error in generator
> *** Term           : showString content
> *** Type           : [Char] -> [Char]
> *** Does not match : IO a
> 
> IO> 
> 
> I know the data type doesn't match. How do i go about this?

Use an adaptor function:

main :: IO ()
main 
     = do
         putStr "Enter input file name.txt: "
         filename <- getLine
         content <- readFile filename
         print $ createIndex content

createIndex  ::  String  ->  [ ([Int], String) ]
createIndex  = undefined


print is a standard library function of type:

print :: Show a => a -> IO ()

That is, it turns any value that can be turned into text, and produces
an action.  Operationally, it displays the passed-in value on standard
output (with a newline). 


More information about the Haskell-Cafe mailing list