O'Reilly logo

Developing Web Applications with Haskell and Yesod by Michael Snoyman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Buffering

Buffering is one of the unique features of conduits. With buffering, conduits no longer need to control the flow of your application. In some cases, this can lead to simpler code.

Inversion of Control

Buffering was actually one of the main motivations in the creation of the conduit package. To see its importance, we need to consider the approach we’ve seen so far, which we’ll call inversion of control, or IoC.

Note

Inversion of control can mean different things in different circles. If you object to its usage here, go ahead replace it with some other phrase like “warm, fuzzy thing.” I won’t be offended.

Suppose you want to count how many newline characters there are in a file. In the standard imperative approach, you would do something like:

  1. Open the file.

  2. Pull some data into a buffer.

  3. Loop over the values in the buffer, incrementing a counter on each newline character.

  4. Return to 2.

  5. Close the file.

Notice that your code is explicitly calling out to other code, and that code is returning control back to your code. You have retained full control of the flow of execution of your program. The conduit approach we’ve seen so far does not work this way. Instead, you would:

  1. Write a sink that counts newlines and adds the result to an accumulator.

  2. Connect the sink to a source.

There’s no doubt in my mind that this is an easier approach. You don’t have to worry about opening and closing files or pulling data from the file. Instead, the data you need to process is simply presented to you. This ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required