Page 1 of 1

Extending FORMAT

Posted: Mon Sep 22, 2008 2:51 am
by humpolec
I want to format my text using FORMAT-like syntax, but with ability to call some other functions, for example
(message "%a" obj) would print (descr obj), and (message "%b" obj) prints (short-descr obj).
I thought of making wrappers to that functions, and using them to with the FORMAT's slash-tilde directive. Then my code can just replace "%a" with "~/my-package::descr-wrapper/" and "%b" with "~/my-package::short-descr-wrapper/" (this is simplified, I would also preserve directive parameters) and pass control to FORMAT itself.
This, however, looks ugly to me (not to mention inefficient, but that doesn't matter much to me). Is there a better way? Would I be better off with writing my own formatting function? Or maybe there is some library that allows for user-extensible FORMAT-like syntax, like what ITERATE is to LOOP?

Re: Extending FORMAT

Posted: Mon Sep 22, 2008 3:31 am
by death
See http://cs-www.cs.yale.edu/homes/dvm/format-stinks.html. The OUT macro is easy to extend.

Re: Extending FORMAT

Posted: Mon Sep 22, 2008 4:49 am
by humpolec
But... I like FORMAT :) (Just as I like printf more than iostreams.) OUT seems to have been invented because FORMAT strings can get too hairy and illegible. I don't think that would be a problem in my case, as I won't be doing anything fancy...

Code: Select all

;; Suppose I want a message like "Monkey hits you with two forks and kills you 
;;  with them."

;; Right now my MESSAGE just calls FORMAT to do the dirty work.

(message "~a hits ~a with ~a and kills ~a with ~a."
                   (descr monst1)
                   (descr monst2)
                   (descr weapon)
                   (pronoun monst2)
                   (pronoun weapon))

;; How I think it'd look with OUT: similar in verbosity to using FORMAT, and
;; in my opinion less legible - I don't like the control original string being sliced
;; across the function call.

(message (:de monst1) " hits " (:de monst2) 
     " with " (:de weapon) 
     " and kills " (:pr monst2)
     " with " (:pr weapon))

;; What I find most elegant (the numbers can translate to a jump directive).

(message "%d hits %d with %d and kills %2p with %3p." monst1 monst2 weapon)

Re: Extending FORMAT

Posted: Mon Sep 22, 2008 5:12 am
by humpolec
Hmm... I read a bit and I see what I want can be very easily done with CL-PPCRE:REGEX-REPLACE-ALL. Yay for Lisp! :)