5 ms·
> 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 evalua
by BeetleB 4mo ago
> 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!
- janalsncm 4mo ago(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.
- BeetleB 4mo agoNo, 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).
- janalsncm 4mo agoOk yeah looking at it again I understand now. Still learning to read.
- gf000 4mo agoWell, 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.
- KingMob 4mo agoThis is true, but thunks carry overhead that macros don't in this case.
- gf000 4mo agoWell, 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.
- BeetleB 4mo agoAnd I know people will think I'm crazy, but thunks are harder to read. (And I have trouble reading macros).