jarod.tian
jarod.tian

Reputation: 31

print arguments of function call without evaluation, not using "macro"

Arguments will be evaluated during a function call in Lisp. Is there any way besides macro to print the argument without evaluation?

Take an example in Common Lisp:

(defun foo (&rest forms)
  (loop for i in forms collect i))

Call "foo" in REPL toplevel:

CL-USER> (foo (= 1 2) (< 2 3))

Got the result:

(NIL T)

Is there any way to get this result?:

((= 1 2) (< 2 3))

Upvotes: 2

Views: 181

Answers (2)

Alexis King
Alexis King

Reputation: 43852

You can’t do that in either Scheme or Common Lisp without macros. Of course, it’s also pretty trivial with macros, so feel free to use them if they fit your use case.

That said, there’s a bit more to this question than you may have anticipated. You’re effectively asking for a feature that was present in older Lisps that has fallen out of fashion, known as fexprs. A fexpr is exactly what you describe: a function whose operands are passed to it without being evaluated.

Most modern dialects have done away with fexprs in favor of only using macros, and you can see this Stack Overflow question for more information on why. The gist is that fexprs are hard to optimize, difficult to reason about, and generally less powerful than macros, so they were deemed both redundant and actively harmful and were summarily removed.

Some modern Lisps still support fexprs or something like them, but those dialects are rare and uncommon in comparison to the relative giants that are Scheme and CL, which dominate the modern Lisp world. If you need this sort of thing, just use macros. Better yet, just quote the arguments so you don’t need any macros at all. You’ll be more explicit (and therefore much clearer), and you’ll get the same behavior.

Upvotes: 8

Kaz
Kaz

Reputation: 58598

Yes; you can get the result with an operator called quote, if you don't mind one more level of nesting:

(quote ((= 1 2) (< 2 3)))
-> ((1 2) (2 3))

quote isn't a macro; it is a special operator.

Upvotes: 2

Related Questions