Skip to content

Instantly share code, notes, and snippets.

@albop
Created November 18, 2013 10:26
Show Gist options
  • Save albop/7525675 to your computer and use it in GitHub Desktop.
Save albop/7525675 to your computer and use it in GitHub Desktop.
zero_based_indexing
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
@ivarne
Copy link

ivarne commented Nov 18, 2013

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment