Dealing with Laziness and IO

When we see the behavior of our program, our first instinct might be to look at how we’re recording the time spent in the histogram code—perhaps we’ve accidentally introduced a bug that causes us to not record times correctly? The fact that we have more reasonable values for our other calls is evidence against this though.

The problem we’ve run into is writeIORef handles the value it’s writing into the reference lazily. Although we’re always writing something into the reference immediately each time we’re calling writeIORef, the value we’re writing isn’t our newly updated histogram. Instead, we’re writing a thunk that contains the computation that will give us an updated histogram when we need it. Creating a thunk ...

Get Effective Haskell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.