Changeset 8729 in project


Ignore:
Timestamp:
02/23/08 23:24:12 (12 years ago)
Author:
mfredrickson
Message:

Adding macro examples showing a task that would be hard with Ruby's eval.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • wiki/chicken-for-ruby-programmers

    r8728 r8729  
    745745your program, which is usually the best time to do it.
    746746
    747   TODO
    748 
     747Scheme macros ''rewrite'' your code during compile time. They can
     748range from simple to complex, with some macros defining entire
     749"sublanguages" embedded in Scheme.
     750
     751Some people call Rails' {{acts_as_foo}} functions macros. This
     752description is not wrong, as these functions do ''rewrite'' your
     753classes in a similar way to Scheme macros, but they are not quite
     754as powerful.
     755
     756Here is a simple example of a task that is easy in Scheme, but
     757much, much harder using Ruby's eval. Say you were debugging a
     758program and found yourself printing out variables at certain
     759points in the execution, along with the name of the variable
     760so you could tell what you were looking at.
     761
     762<enscript highlight=scheme>
     763  (print "myvar: " myvar)
     764</enscript>
     765
     766You decide that repeatedly typing the variable name twice (once to
     767indicate which variable, once to get the value) is a waste of time.
     768Using a macro, you can quickly and easily abstract away the common
     769syntax into one place.
     770
     771<enscript highlight=scheme>
     772  (define-macro (ez-debug var)
     773    (let ((name (symbol->string var)))
     774      `(print ,name ": " ,var)))
     775   
     776  (define myvar '(this is a list))
     777
     778  (ez-debug myvar)
     779</enscript>
     780
     781This simply wouldn't be possible with a function. By the time a
     782procedure is called, syntactic information like variables names
     783has been optimized away.
     784
     785
Note: See TracChangeset for help on using the changeset viewer.