preprocessing printf/regex strings (like ocaml)

Martin Norbäck d95mback@dtek.chalmers.se
14 May 2002 11:34:39 +0200


--=-3fMmjUHk1Os5MTvT3ceV
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

tis 2002-05-14 klockan 06.37 skrev anatoli:
> Brian Huffman <bhuffman@galois.com> wrote:
> > Here is a printf-style function that I hacked up this morning; it uses =
type

> > classes but it doesn't need functional dependencies:
> [snip]
>
> It's very nice and even extendable, though `class Printf String'
> is unfortunately not Haskell 98. But the bigger question is, how
> to support Posix-style positional arguments? They are essential for
> i18n.
>
> For instance,
>
> > printf "%1$s %2$s" "foo" "bar" -- =3D=3D> "foo bar"
> > printf "%2$s %1$s" "foo" "bar" -- =3D=3D> "bar foo"
>
> Naturally, such format strings cannot be pre-processed by the
> compiler since they are typically loaded from some message database
> at run time.

I agree that i18n needs positional arguments.
What's wrong with simply doing like this:

printf "I have %. %. %.."    ["trained", show 1, "Jedi"]
printf "%2. %3. %1. I have." ["trained", show 1, "Jedi"]

with printf would look something like this:

printf ('%':'%':rest) xs     =3D '%' : printf rest xs
printf ('%':'.':rest) (x:xs) =3D x ++ printf rest xs
printf ('%':d:rest)   xs     | isDigit d =3D
  let (ds, rest') =3D span isDigit rest
      index =3D read (d:ds)
  in if null rest' || head rest' /=3D '.' || index > length xs then
       '%':printf (d:ds:rest') xs
     else
       xs!!(index - 1) ++ printf (tail rest') xs
printf (r:rest) xs =3D r:printf rest xs=20
printf [] _ =3D []

Note that there are no errors if the format string is wrong in any way, it'=
s
just unchanged. Also, behaviour with both positional and normal
formatters is not considered.

Feel free to use this code snippet however you like.

Regards,

	Martin

--
Martin Norb=E4ck          d95mback@dtek.chalmers.se
Kapplandsgatan 40       +46 (0)708 26 33 60
S-414 78  G=D6TEBORG      http://www.dtek.chalmers.se/~d95mback/
SWEDEN                  OpenPGP ID: 3FA8580B

--=-3fMmjUHk1Os5MTvT3ceV
Content-Type: application/pgp-signature; name=signature.asc

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: För information se http://www.gnupg.org/

iD8DBQA84NovkXyAGj+oWAsRAm4xAJ4mnzJDJn6p0EqibqOSY/9Rt8Zm/gCgimzf
MvttZC3PqY26zuU7nZl4B+Q=
=tFj1
-----END PGP SIGNATURE-----

--=-3fMmjUHk1Os5MTvT3ceV--