I was reading the answer to this question: Haskell: difference between . (dot) and $ (dollar sign) And the reply struck me as odd… What does he mean + has no input? And then I tried:
((+) 1)
((+) 1 1)
((+) 1 1 1)
Whoops… sad news. But I’m sure I saw functions that can take seemingly arbitrary or a very large number of arguments to believe that someone had defined them in a way a->b->c…->z. There must be some way to handle it! What I’m looking for is something like &rest or &optional in CL.
Sure, you can define a variadic addition function, with some typeclass hackery:1
And so:
The same trick is used by the standard
Text.Printfmodule. It’s generally avoided for two reasons: one, the types it gives you can be awkward to work with, and you often have to specify an explicit type signature for your use; two, it’s really a hack, and should be used rarely, if at all.printfhas to take any number of arguments and be polymorphic, so it can’t simply take a list list, but for addition, you could just usesum.1 The language extension isn’t strictly necessary here, but they make the usage easier (without them, you’d have to explicitly specify the type of each argument in the examples I gave, e.g.
add (1 :: Integer) (2 :: Integer) :: Integer).