[Haskell-cafe] file i/o

Neil Mitchell ndmitchell at gmail.com
Tue Jan 3 06:33:46 EST 2006

Hi Robert,

The first thing to mention is that Haskell uses linked-lists, not
arrays as the "standard" list type structure, so [1,2] is actually a
linked list.

The next thing to note is that Haskell is *lazy*. It won't do work
that it doens't have to. This means that you can return a linked list
with all the lines in the file, but they won't actually be read til
they are required. i.e. Haskell cleverly worries about all the
"getting a next line as required" stuff, without you even noticing -
it will read it line by line.

A simple function that does some of what you want is:
> parseFile :: FilePath -> IO [(String, [Int])]
> parseFile x = do src <- readFile x
>                          return (map parseLine (lines src))

> parseLine :: String -> (String, [Int])
> parseLine = for you to write :)

The other point is that Haskell linked lists have to have every
element of the same type, so you can't have ["test",1] as a linked
list, what you actually want is a tuple, written ("test",1) - a tuple
is of fixed length and all elements can be of different type.

Hope that helps,


More information about the Haskell-Cafe mailing list