Politics, Programming and Possibilities
18 Jul
One of Haskell’s touted features is “lazy evaluation”. I’m starting to see the bigger picture with this language feature, and the following example really helped me. From Real World Haskell:
[The method]
hGetContentsis different [from the traditional open/read/close method of accessing files]. The String it returns is evaluated lazily. At the moment you callhGetContents, nothing is actually read. Data is only read from the Handle as the elements (characters) of the list are processed. As elements of the String are no longer used, Haskell’s garbage collector automatically frees that memory. All of this happens completely transparently to you. And since you have what looks like—and, really, is—a pure String, you can pass it to pure (non-IO) code.
Lazy evaluation is the ability to describe a model for all possible scenarios, and then compute just the scenario you need, on demand. In this case, “all possible scenarios” is any sequence of bytes, read from disk. As mentioned in the book, lazy evaluation of a file’s contents means you can read gigabytes of file contents without having to worry about buffering, chunking, looping, or garbage collection. Sweet!
Leave a reply