Skip to content
Browse files

adding @staged in examples/

  • Loading branch information...
1 parent 3ace3d8 commit 027d587e2d36c2b3405efdd7378fbbef275e273e @JeffBezanson JeffBezanson committed Jun 6, 2012
Showing with 59 additions and 0 deletions.
  1. +59 −0 examples/staged.jl
View
59 examples/staged.jl
@@ -0,0 +1,59 @@
+function _jl_add_method(gf, an, at, body)
+ argexs = { expr(symbol("::"), an[i], at[i]) for i=1:length(an) }
+ def = quote
+ let __F__=($gf)
+ function __F__($(argexs...))
+ $body
+ end
+ end
+ end
+ eval(def)
+end
+
+macro staged(fdef)
+ if !isa(fdef,Expr) || !is(fdef.head,:function)
+ error("@staged: expected method definition")
+ end
+ fname = fdef.args[1].args[1]
+ argspec = fdef.args[1].args[2:]
+ argnames = map(x->(isa(x,Expr) ? x.args[1] : x), argspec)
+ qargnames = map(x->expr(:quote,{x}), argnames)
+ fbody = fdef.args[2]
+ @gensym gengf argtypes expander genbody
+ quote
+ let ($gengf)
+ global ($fname) # should be "outer"
+ local ($expander)
+ function ($expander)($(argnames...))
+ $fbody
+ end
+ ($gengf)() = 0 # should be initially empty GF
+ function ($fname)($(argspec...))
+ ($argtypes) = typeof(tuple($(argnames...)))
+ if !method_exists($gengf, $argtypes)
+ ($genbody) = apply(($expander), ($argtypes))
+ _jl_add_method($gengf, {$(qargnames...)},
+ $argtypes, $genbody)
+ end
+ return ($gengf)($(argnames...))
+ end
+ end
+ end
+end
+
+# example
+
+@staged function nloops(dims::Tuple)
+ names = map(x->gensym(), dims)
+ ex = quote
+ println([$(names...)])
+ end
+ for i = 1:length(dims)
+ ex = quote
+ for ($names[i]) in dims[$i]
+ $ex
+ end
+ end
+ end
+ ex
+end

1 comment on commit 027d587

@StefanKarpinski
The Julia Language member

Using dims::Tuple as the only example is a bit confusing since Tuple is both a type and a kind.

Please sign in to comment.
Something went wrong with that request. Please try again.