POV-Ray : Newsgroups : povray.off-topic : Haskell raving : Re: Haskell raving Server Time
12 Oct 2024 03:16:48 EDT (-0400)
  Re: Haskell raving  
From: nemesis
Date: 31 Oct 2007 13:25:00
Message: <web.4728c74c7b4224e7773c9a3e0@news.povray.org>
Warp <war### [at] tagpovrayorg> wrote:
> Tim Attwood <tim### [at] comcastnet> wrote:
> > readFile "filename" >>= process
>
>   Btw, how do you actually read the contents of the file in haskell with
> a command like that? What is the unit type? Can you read, for example,
> one byte at a time? What if you would want to parse an ascii-formatted
> input file, for example? How is it done exactly?

http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3AreadFile

readFile returns a String.  But don't despair:  it won't fill the whole memory
with a giant string for large files!  Lazyness means values are only evaluated
once needed.  If you just take the whole contents, yes, you'll be sorry.
Otherwise, you can use a function like "take 5 string" and it'll only take the
first five characters (a string is merely a list of characters in Haskell).
You may process it with folds or other higher-order functions.

To ilustrate lazyness in a simple REPL example:
ones = 1:ones
take 5 ones
take 5 (map (*2) ones)

ones is of course an infinite, recursively-defined list.  If you just evaluate
it at the prompt, the REPL will begin filling your screen with ones or worse
(like filling your memory).  The same for simply doing map (*2) ones which will
try to double every 1 in ones.

But lazyness means we can restrict the evaluated value to just a few members
from this infinite data structure, which is what we do by taking one a few.

So, with lazyness, size really doesn't matter.

Of course, there are other useful IO functions out there that offer more control
over opening/closing file handles etc.


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.