Created
November 18, 2013 10:26
-
-
Save albop/7525675 to your computer and use it in GitHub Desktop.
zero_based_indexing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rewrite(x::Number) = x | |
rewrite(x::Symbol) = x | |
rewrite(x::String) = x | |
function rewrite(expr) | |
if expr.head == :ref | |
return Expr(expr.head, expr.args[1], [rewrite(:( 1 + $i)) for i in expr.args[2:end]]...) | |
else | |
return Expr(expr.head, [rewrite(i) for i in expr.args]...) | |
end | |
end | |
macro zero_index(expr) | |
eval( rewrite(expr) ) | |
end | |
@zero_index begin | |
a = [67,90] | |
b = [0,1] | |
c = [ [4 3];[2 5] ] | |
x1 = a[0] | |
x2 = a[b[1]] | |
x3 = c[b[0], 1] | |
println( string("\nShould be 67 : ", x1 )) | |
println( string("\nShould be 90 : ", x2 )) | |
println( string("\nShould be 3 : ", x3 )) | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you should return the expression without eval. The expression gets evaluated when the function returns anyway. If you use this inside a function you will eval the zero index part only once, and you probably will get errors because of undefined variables.