[Haskell-cafe] Re: Pure Haskell Printf

John Goerzen jgoerzen at complete.org
Tue Nov 16 09:43:56 EST 2004


On 2004-11-16, Peter Simons <simons at cryp.to> wrote:
> > I know memory is expensive, that's why only the last two
> > digits of year numbers are stored. :-]
>
> I understand what you're getting at -- and I find it
> annoying, too, when people sacrifice robustness for comfort.

In this particular case, the printf functions without the leading "v"
operate on a list in the manner some have suggested.

I find the "v" forms preferable since they are easier to type, though I
understand the case against them.

> the conclusion that for this particular use-case hard-coded
> place-holders (like %s, %d, etc.) are not that useful. You'd
> like to be able to (easily!) extend the function, to offer a
> more general variable substitution, like sh(1) does. So that
> you could write
>
>   Dear ${customer},

Indeed, I've already done that in the Python style.  From [1]:


-----------------
As a special extension to the printf() format string syntax, special
functions can take a key name in the format string. This key will then
be looked up in an association list or FiniteMap passed in. Python
programmers will find this very similar to Python's % operator, which
can look up inside dicts. 




Here's an example: 

import MissingH.Printf

al = [("item1", v "Test One"),
      ("blah", v (5::Int)),
      ("zip", v (3.14::Float))]

main :: IO ()
main = do
       printfAL "%(item1)s: %(blah)03d, %(zip)06.3f; %(item1)s\n" al


This will print: 

Test One: 005, 03.140; Test One
-------------------

There are also printfFM functions that work with FiniteMaps in a similar
manner.

[1] http://gopher.quux.org:70/devel/missingh/html/MissingH.Printf.html#6



More information about the Haskell-Cafe mailing list