With-Resource Puzzle

If you want to use a file in Haskell, you have two options. You can open and close the file yourself:

… or you can use a function that takes care of the open-close lifecycle:

Which is the better interface? It’s a trade-off: withFile  guarantees that every open file is closed, while openFile and hClose allow you to open and close files in any order.

Let’s create types to represent these two kinds of interface:

Is it possible to convert between the two? Here’s how to obtain a With  interface from an OpenClose  interface:

It’s also possible to obtain an OpenClose  interface from a With  interface. Can you see how?

(answer here)

(first posted here)

— Ashley Yakeley

Leave a Reply