G
Greg Fodor
A common pattern seen in a lot of ruby code is:
g(m(x)) if/unless/while/until h(m(x))
for example,
puts "User: #{opts[:user]}" if opts[:user]
in this case, g(x) = puts "User: #{x}", h(x) = x, and m(x) =
opts[:user]
or
return v+1 if v +1 < 10
In this case, g(x) = x, h(x) = x < 10, and m(x) = v + 1
This is obviously suboptimal code, as is, because it results in the
evaluation of m(x) twice. I propose a new keyword is added, "it",
which may appear within the statement to the left of the decorator.
So, the previous statements become:
puts "User: #{it}" if opts[:user]
and
return it if |v + 1| < 10
If and only if "it" is seen on the left hand side, the ruby
interpreter should store the expression result on the conditional into
a temporary storage and evaluate that as "it". It falls out of scope
after the statement. The use of pipes can designate a subexpression to
use for "it" instead (I don't have my heart set on pipes, but you get
the idea.)
This keyword allows better DRY in ruby for this g(m(x)) op h(m(x))
pattern and also provides a nice optimization since your average lazy
programmer will usually evaluate m(x) twice instead of putting it into
temporary local storage themselves. By promoting it to a keyword, you
also prevent the problems seen here: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/166828
Thoughts?
g(m(x)) if/unless/while/until h(m(x))
for example,
puts "User: #{opts[:user]}" if opts[:user]
in this case, g(x) = puts "User: #{x}", h(x) = x, and m(x) =
opts[:user]
or
return v+1 if v +1 < 10
In this case, g(x) = x, h(x) = x < 10, and m(x) = v + 1
This is obviously suboptimal code, as is, because it results in the
evaluation of m(x) twice. I propose a new keyword is added, "it",
which may appear within the statement to the left of the decorator.
So, the previous statements become:
puts "User: #{it}" if opts[:user]
and
return it if |v + 1| < 10
If and only if "it" is seen on the left hand side, the ruby
interpreter should store the expression result on the conditional into
a temporary storage and evaluate that as "it". It falls out of scope
after the statement. The use of pipes can designate a subexpression to
use for "it" instead (I don't have my heart set on pipes, but you get
the idea.)
This keyword allows better DRY in ruby for this g(m(x)) op h(m(x))
pattern and also provides a nice optimization since your average lazy
programmer will usually evaluate m(x) twice instead of putting it into
temporary local storage themselves. By promoting it to a keyword, you
also prevent the problems seen here: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/166828
Thoughts?