Skip to content

Instantly share code, notes, and snippets.

@trans
Created June 2, 2014 16:47
Show Gist options
  • Save trans/a0f57326c647a19bcf48 to your computer and use it in GitHub Desktop.
Save trans/a0f57326c647a19bcf48 to your computer and use it in GitHub Desktop.
Postponed Evaluation of Arguments
# Postponed Evaluation of Arguments
Today in Ruby, there are a few special `methods' in that they do not seem to evaluate their arguments. An example is alias, which contrary to Module#alias_method does not take symbols as arguments, but instead takes the method names directly. This cannot be done by pure Ruby code as the method name would be evaluated by calling the method and taking the return value as the actual value of the parameter. The idea would be to give a method control over this. There are lots of unanswered questions though:
Languages like Lisp can do this in their macros because code is data and can easily be manipulated. In Ruby, code is not data (yet). It would be nice if it could be data. This requires the representation of a parse tree (although that may change with the advent of YARV) that can be inspected or even manipulated. This would be a powerful tool by itself, but at least inspection is required to make full use of the idea of postponed evaluation of arguments.
How is it indicated that an argument should not be evaluated? And how do we later on indicate when we want to evaluate it?
The arguments, if evaluated later on anyway, should be evaluated in the binding of the caller. Or at least it should be possible to do so. This incurs a whole context switch, which is expensive. So it should only be used when necessary.
This would allow some cool things, like writing a Polynomial class that can be called like this
Polynomial.new(x**2 + 2*x + 1)
The constructor specifies postponed evaluation of its argument, and just inspects its argument to see whether the expression is a polynomial and constructs its internal data structures correspondingly.
Funny realization: does this make blocks obsolete?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment