Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type-safe printf

The standard library provides a printf function which manages to be varadic. What it doesn't do, however, is compile-time checking of whether the argument types match the format string. That would require dependent types, and it sounds like it would be really hard to implement too! (You'd have to parse the entire format string using type signatures... yuck!)

But on reflection, now I'm wondering... Can we do this with Template Haskell? In fact, has anybody written a library for this already??

(It looks like you could fairly easily write a quasi-quoter that reads a printf format spec and generates the necessary N-arg function...)

like image 505
MathematicalOrchid Avatar asked Jan 05 '13 21:01

MathematicalOrchid


2 Answers

Yes, it's possible. Yes, it's been done. You should really check hackage for this kind of question: http://hackage.haskell.org/package/Printf-TH

like image 184
Carl Avatar answered Sep 28 '22 15:09

Carl


If you are willing to accept that the "format string" isn't really a string, then you can implement a printf-like function directly in Haskell, too.

This has been described, for example, in a paper by Ralf Hinze, called "Formatting: a class act". On Hackage, I can only find the xformat package implementing something similar to this approach.

like image 44
kosmikus Avatar answered Sep 28 '22 16:09

kosmikus