Appendix C. Settings Types

Let’s say you’re writing a web server. You want the server to take a port to listen on, and an application to run. So you create the following function:

run :: Int -> Application -> IO ()

But suddenly you realize that some people will want to customize their timeout durations. So you modify your API:

run :: Int -> Int -> Application -> IO ()

So, which Int is the timeout, and which is the port? Well, you could create some type aliases, or comment your code. But there’s another problem creeping into the code: this run function is getting unmanageable. Soon you’ll need to take an extra parameter to indicate how exceptions should be handled, and then another one to control which host to bind to, and so on.

A more extensible solution is to introduce a settings data type:

data Settings = Settings
    { settingsPort :: Int
    , settingsHost :: String
    , settingsTimeout :: Int
    }

And this makes the calling code almost self-documenting:

run Settings
    { settingsPort = 8080
    , settingsHost = "127.0.0.1"
    , settingsTimeout = 30
    } myApp

Great—couldn’t be clearer, right? True, but what happens when you have 50 settings to your web server? Do you really want to have to specify all of those each time? Of course not. So instead, the web server should provide a set of defaults:

defaultSettings = Settings 3000 "127.0.0.1" 30

And now, instead of needing to write that long bit of code, you can get away with:

run defaultSettings { settingsPort = 8080 } myApp -- (1)

This is great, except ...

Get Developing Web Apps with Haskell and Yesod, 2nd Edition 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.