Haskell Problem

José Romildo Malaquias [email protected]
Tue, 10 Oct 2000 15:49:59 -0200


On Tue, Oct 10, 2000 at 07:11:14PM +0100, Graeme Turner wrote:
> The basic aim is to read in a file of data, sort it and then display it.
> 
> I have managed to get a sort to function properly but I am having trouble
> with reading in the data from the file. I have managed to use the
> hGetContents and hGetLine methods of the IO library to read the data in but
> when it is read in, it is stored as an IO String type.
> 
> I would like to convert the input from the file into one large string so I
> can process it before sorting it.
> 
> After reading the whole file into a variable, how do I then convert that IO
> String to a String?

You do not have to convert from the abstract data type IO String into String.
You can access the string encapsulated in such abstract data type
using monad operations. The type IO String is the type of the computations
that perform input/output and produces a string as their result. You
can pass this result as an argument to a function of type String -> IO a
which may do the desired manipulation on the string and may also perform
some more input/output and should produce a result of type a.

The do expression is used for sequencing computations, possibly binding
their results to variables, which can then be used in subsequent
computations.

For example, suppose you want to write to standard output the number
of characters read from standard input:

module Main where
import Prelude
main :: IO ()
main = do xs <- getContents
	  putLine (show (length xs))

This program has two computations. The first one, getContents, read
all available characters from standard input and binds the resulting
string to the variable xs. The second one, putLine (show (length xs)),
finds the length of the string, converts the resulting integer to string
and writes it to standard output.

In your case you may write something similar that sort the input,
instead of find its length.

Romildo
-- 
Prof. José Romildo Malaquias <[email protected]>
Departamento de Computação
Universidade Federal de Ouro Preto
Brasil