[Haskell-cafe] file i/o

Thomas Davie tom.davie at gmail.com
Tue Jan 3 06:49:04 EST 2006

The other thing to mention, is that if you have the ability to change  
file formats, it may be better to make just a slight adjustment... If  
you make it look exactly like the haskell data structure you want:

[("Foo", [1,2,3,4,5,6,7])
,("Bar", [7,6,5,4,3,2,1])

Then your parser becomes even simpler:

parseFile :: FilePath -> IO [(String,[Int])]
parseFile = do src <- readFile x
                            return $ read src

On Jan 3, 2006, at 11:33 AM, Neil Mitchell wrote:

> 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,
> Neil
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

More information about the Haskell-Cafe mailing list