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

Appendix D. 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 our code: this run function is getting unmanageable. Soon we’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.

So 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 above, we can get away with:

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

This is great, except for ...

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