[Haskell-cafe] Idiomatic Haskell equivalent of "keyword arguments" to functions

Neil Mitchell ndmitchell at gmail.com
Fri Dec 29 17:32:48 EST 2006

Hi Paul,

> To make things concrete, the example I'm really thinking of is a "send
> an email" function, which would take a subject, a body, a list of
> recipients, optional lists of cc and bcc recipients, an optional
> mailserver (default localhost), an optional port (default 25), and
> possibly optional authentication details.

Records are your friend.

data Email = Email {subject :: String, body :: String, to ::
[Address], cc = [Address], bcc = [Address], mailserver :: String, port
:: Int}

defaultEmail = Email{subject = "No subject", body = "", to = [], cc =
[], bcc = [], mailserver = "localhost", port = 25}

The user can then go:

sendEmail defaultEmail{subject="Subject here", body = "body here", to
= ["haskell-cafe"], mailserver = "server.haskell.org"}

Now things which are't specified (port) keep their default value.

The other alternative is:

data EmailParams = Body String
                            | Port Int
                            | Mailserver String


sendEmail [Body "body here", To "haskell-cafe", Mailserver
"server.haskell.org" ...]

I prefer the first, but the second can also be done.



More information about the Haskell-Cafe mailing list