> But I don't understand how that's different than a function which evaluates other functions.
You want a function that takes in arguments, but does not evaluate the arguments when called. So:
func(foobar(), foobar())
Normally, foobar() will be called twice - at the time of the call. With macro expansion, you can ensure that it's not the result of calling foobar that goes into the func, but this expression.A canonical example is if you want to write an if/then/else function:
if(condition, then_path, else_path)
It's quite possible that the else_path is invalid and will terminate the program if the condition is true. But if you wrote a function this way, it will evaluate both then_path and else_path - not something you want to do in a regular if expression!
(I think you meant “if condition is false”)
Technically you can accomplish the same thing in languages with first class functions if the caller wraps their code in a lambda.
No, I meant "if condition is true".
The point is that in most/all languages, if the condition is true, the else branch is not evaluated. And it's usually OK to put code in there that can crash when the condition is true, because we know it won't be evaluated.
But if you make an if function like I did above in, say, Python, both the then_path and the else_path are evaluated before the decision is made.
> Technically you can accomplish the same thing in languages with first class functions if the caller wraps their code in a lambda.
True. For languages that have lambdas (which I guess is most of them nowadays).
Well, as mentioned that's why you create two lambdas as the branches. This is pretty much what thunks are in some languages (like Haskell), so this example doesn't strictly require macros per se.
This is true, but thunks carry overhead that macros don't in this case.
And I know people will think I'm crazy, but thunks are harder to read.
(And I have trouble reading macros).
Well, if we have a compiler that sees a constant value, it can completely optimize out one branch. But it of course depends on the semantics of the language.
But yeah you are right in case of a naive compiler.
Ok yeah looking at it again I understand now. Still learning to read.