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:
dataSettings=Settings{settingsPort::Int,settingsHost::String,settingsTimeout::Int}
And this makes the calling code almost self-documenting:
runSettings{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=Settings3000"127.0.0.1"30
And now, instead of needing to write that long bit of code above, we can get away with:
rundefaultSettings{settingsPort=8080}myApp-- (1)
This is great, except for ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access