• [^] # Re: Intéressant

    Posté par (site web personnel) . En réponse au journal Troll de l'année ou coup de bluff ?. Évalué à 3.

    Voila ce que j'appele une macro en Lisp :
    • Définir un nouveau type de boucle :
      (defmacro while (test &body body)
       `(do ()
       ((not ,test))
       ,@body))
      (let ((a 1))
       (while (< a 10)
       (print a)
       (incf a)))
      Dans le même style, la macro loop est assez impressionnante.
    • Le if anaphorique :
      (defmacro aif (test then &optional else)
       `(let ((it ,test)) (if it ,then ,else)))
      (defun un-calcul-super-long ()
       (sleep 10)
       (+ 2 2))
      (aif (un-calcul-super-long) (print it))
      
      La variable 'it' prend le résultat de la fonction 'un-calcul-super-long'
    • Une macro de débogage :
      (defmacro dbg (&rest forms)
       `(progn
       ,@(mapcar #'(lambda (form)
      		 `(format t "~A=~S " ',form ,form))
      	 forms)
       (format t "~%")
       (force-output)))
      (dbg a str (+ 2 3 4))
      A=12 STR="toto" (+ 2 3 4)=9
      (macroexpand-1 '(dbg a str (+ 2 3 4)))
      (PROGN
       (FORMAT T "~A=~S " 'A A)
       (FORMAT T "~A=~S " 'STR STR)
       (FORMAT T "~A=~S " '(+ 2 3 4) (+ 2 3 4))
       (FORMAT T "~%")
       (FORCE-OUTPUT))
      
    Peut-on faire la même chose en C ?