[Haskell-cafe] Generic polyvariadic printf in Haskell98

oleg at okmij.org oleg at okmij.org
Fri Jun 5 03:57:00 EDT 2009

Evan Klitzke wrote:

> I'm writing code with hslogger, and I'm finding myself frequently
> writing things like this:
> infoM $ printf "%s saw %s with %s" (show x) (show y) (show z)

Indeed writing these `show' is tedious. Fortunately, we can get rid of
them, still remaining in Haskell98. The following file defines the
polyvariadic generic printf:

It is like polyvariadic show with the printf formatting string. It
handles values of any type for which there is a Show instance. Two
instances of the class SPrintF are all we ever need.

Here are the tests:

t1 = unR $ printf "Hi there"
-- "Hi there"

t2 = unR $ printf "Hi %s!" "there"
-- "Hi there!"

t3 = unR $ printf "The value of %s is %s" "x" 3
-- "The value of x is 3"

t4 = unR $ printf "The value of %s is %s" "x" [5]
-- "The value of x is [5]"

The appearance of unR is only because of Haskell98 (with flexible
instances, we can get rid of that). On the other hand, your code
post-processes the result of formatting with infoM, so the newtype
unwrapping should not matter at all.

Still, the code is a bit unsatisfactory because of the appearances of
"error" in pr_aux functions. The errors like passing too many or too
few arguments to printf (as demanded by the format specification) are
caught only at run-time. We can certainly do better.

More information about the Haskell-Cafe mailing list