Hacker News new | ask | show | jobs
by jcl 6569 days ago
I too am not very experienced in Lisp, but one rule of thumb I have seen for macros is: "If you don't want to automatically evaluate all the arguments of a function, use a macro instead."

As you point out, macros can be overused, but there are some things that you can do with macros that simply can't be done with functions alone (like implementing short-circuiting "and"s and "or"s using just "if" statements).

Many syntactic sugar improvements to programming languages -- like .NET's "using" statement, which allocates a resource, runs some code, then frees the resource -- can be implemented directly with macros. These improvements make code shorter, easier to read, and less error-prone... and with macros you don't have to wait for the language designer to add that functionality for you.

1 comments

Most languages short-circuit ands and ors already, but adding additional short-circuiting demands macros:

My practical example of this is my desire for a short-circuit "implies" operator to use in assertions (typically in post-conditions).

I want to able to write checks like

  assert (foo != null _implies_ foo.someProperty);
where the _implies_ operator short-circuits.

Writing my own implies(a,b) function is no good in most languages, because strict evaluation would yield a null-reference exception in the example when a is null.

Without macros I end-up writing:

  assert(a == null || a.someProperty); 
or worse

  if (a != null) { assert(a.someProperty);

With lisp-strength macros I could easily add an implies operator and get readable rather than clever code.