Re: [julia-users] macro: with

2016-10-09 Thread Tom Breloff
Heh... it took a google search to figure out where I put it.

https://github.com/tbreloff/CTechCommon.jl/blob/master/src/macros.jl#L113-L155

On Sun, Oct 9, 2016 at 12:19 PM, Ben Lauwens  wrote:

> Hi Tom
>
> I am interested. I am building a macro mimicking how iterator blocks are
> transformed in a state-machine in C# (as an alternative to Tasks) and this
> is one of the (many) thinks I have to solve. Can you point me to the
> source? Thanks
>
> Ben


[julia-users] macro: with

2016-10-09 Thread Ben Lauwens
Hi Tom

I am interested. I am building a macro mimicking how iterator blocks are 
transformed in a state-machine in C# (as an alternative to Tasks) and this is 
one of the (many) thinks I have to solve. Can you point me to the source? Thanks

Ben

[julia-users] macro: with

2016-09-07 Thread Tom Breloff
Hey all... I just threw together a quick macro to save some typing when
working with the fields of an object.  Disclaimer: this should not be used
in library code, or in anything that will stick around longer than a REPL
session.  Hopefully it's self explanatory with this example.  Is there a
good home for this?  Does anyone want to use it?

julia> type T; a; b; end; t = T(0,0)
T(0,0)

julia> macroexpand(:(
   @with t::T begin
   a = 1
   b = 2
   c = a + b - 4
   d = c - b
   a = d / c
   end
   ))
quote  # REPL[3], line 3:
t.a = 1 # REPL[3], line 4:
t.b = 2 # REPL[3], line 5:
c = (t.a + t.b) - 4 # REPL[3], line 6:
d = c - t.b # REPL[3], line 7:
t.a = d / c
end

julia> @with t::T begin
   a = 1
   b = 2
   c = a + b - 4
   d = c - b
   a = d / c
   end
3.0

julia> t
T(3.0,2)


[julia-users] Macro to generate equivalent types

2016-05-19 Thread Tom Breloff
I have a pattern that I frequently use, and I'm considering writing a macro 
to automate it, but figured I'd check if it exists already.

I frequently want to have the equivalent of an existing type functionally, 
but I want to be able to either dispatch on it or include additional fields 
for other purposes.  An example is wrapping a dictionary:

julia> immutable MyDict{K,V} <: Associative{K,V}
 d::Dict{K,V}
 otherfield::Int
   end


julia> md = MyDict(Dict(:x=>1), 10)
Error showing value of type MyDict{Symbol,Int64}:
ERROR: MethodError: `length` has no method matching length(::MyDict{Symbol,
Int64})


julia> md[:x]
ERROR: MethodError: `get` has no method matching get(::MyDict{Symbol,Int64}, 
::Symbol, ::Symbol)
Closest candidates are:
  get(::ObjectIdDict, ::ANY, ::ANY)
  get{K,V}(::Dict{K,V}, ::Any, ::Any)
  get{K}(::WeakKeyDict{K,V}, ::Any, ::Any)
  ...
 in getindex at dict.jl:282
 in eval at REPL.jl:3


julia> Base.length(md::MyDict) = length(md.d)
length (generic function with 111 methods)


julia> md
MyDict{Symbol,Int64} with 1 entryError showing value of type MyDict{Symbol,
Int64}:
ERROR: MethodError: `start` has no method matching start(::MyDict{Symbol,
Int64})
 in isempty at iterator.jl:3
 in showdict at dict.jl:93
 in writemime at replutil.jl:36
 in display at REPL.jl:114
 in display at REPL.jl:117
 [inlined code] from multimedia.jl:151
 in display at multimedia.jl:163
 in print_response at REPL.jl:134
 in print_response at REPL.jl:121
 in anonymous at REPL.jl:624
 in run_interface at ./LineEdit.jl:1610
 in run_frontend at ./REPL.jl:863
 in run_repl at ./REPL.jl:167
 in _start at ./client.jl:420

# the pain continues...



I'd like to be able to automatically do "md[:x]" and have it work, but 
instead I have to define a bunch of Base methods where I simply re-call the 
method with "md.d".

The macro I have in mind would grab the immediate supertype of the type in 
question, make the new type a subtype of that supertype, and then define 
pass-through methods for anything in the "methodswith(Dict)" list.

Does this exist already?  Could I get myself in trouble somehow by defining 
pass-through methods like this?

Thanks!
Tom


Re: [julia-users] Macro as decorators

2016-05-09 Thread Kevin Squire
Possibly.

Do you have a specific example in mind?  That will probably get you a less
ambivalent answer. :-)

Cheers,
   Kevin

On Monday, May 9, 2016, Ford Ox  wrote:

> Is it possible to write macro that will work as python decorator?


[julia-users] Macro as decorators

2016-05-09 Thread Ford Ox
Is it possible to write macro that will work as python decorator? 

Re: [julia-users] Macro expansion for ccall with tuple argument

2016-04-07 Thread Yichao Yu
> and I programmed it as
> julia> macro do_ccall(f,args...)
> :(ccall(f,Int,$(ntuple(i->Int,length(args))),args...)) end

I belive the arguments should be a tuple expression which you can
generate with Expr(:tuple, [Int for i in 1:length(args)]...)

> julia> macroexpand(:(@do_ccall(f,1,2,3)))
> :(ccall(f,Int,(Int64,Int64,Int64),args...))
>

In general you can use `Meta.show_sexpr` (or `dump`/`xdump`) to see
more precisely what the expression is.


[julia-users] Macro expansion for ccall with tuple argument

2016-04-07 Thread Laurent Bartholdi
Hi,
I'm trying to understand macro expansion, and am a bit stuck. I would like, 
in distilled form, to have a macro "@do_ccall" which calls its argument 
with Int type. Thus I would like

julia> macroexpand(:(@do_ccall(f,1,2,3)))
:(ccall(f,Int,(Int64,Int64,Int64),args...))

and I programmed it as
julia> macro do_ccall(f,args...) 
:(ccall(f,Int,$(ntuple(i->Int,length(args))),args...)) end
@do_ccall (macro with 1 method)

Now the tuple argument just doesn't seem to get interpreted properly:

julia> @do_ccall(C_NULL,1,2,3)
ERROR: syntax: ccall argument types must be a tuple; try "(T,)"
 in eval(::Module, ::Any) at ./boot.jl:237

(note: calling the routine at C_NULL would have crashed Julia; it's just 
for demonstration purposes)

Thanks in advance! Laurent


Re: [julia-users] Macro hygiene issue

2016-03-02 Thread Cedric St-Jean
Thank you, that solved it.

On Wed, Mar 2, 2016 at 10:54 AM, Yichao Yu  wrote:

> On Wed, Mar 2, 2016 at 10:51 AM, Cedric St-Jean 
> wrote:
> > Hi, I have a situation that looks a bit like this:
> >
> > module A
> > function foo end
> > end
> >
> > module B
> > import A: foo
> > macro define_foo(typ, value)
> > :(foo(::$(esc(typ))) = $(esc(value)))
> :(A.foo(...) = ...)
> > end
> > end
> >
> > module C
> > using B: @define_foo
> > @define_foo Int 19
> > end
> >
> > A.foo(20)
> >
> > In other words, A is defining a function foo, B defines a macro to define
> > methods of foo, and C uses the macro. This looks like it should work,
> but it
> > doesn't, because hygiene takes over and `foo` gets replaced with a
> gensym in
> > its expansion, since it's on the left-hand-side of an equality. Is there
> any
> > way around this?
>


[julia-users] macro esc nested @everywhere issue

2016-02-18 Thread thr
Hi,

I can't explain the behaviour of this:

macro wtf1()
return esc(
:(begin
@show a
@everywhere const b = a
@show b
end))
end

macro wtf2()
return esc(
:(begin
@show c
const d = c
@show d
end))
end

@everywhere const a = 0
@wtf1
@everywhere const a = 1
@wtf1
@everywhere const a = 2
@wtf1

println()

const c = 0
@wtf2
const c = 1
@wtf2
const c = 2
@wtf2

results in:

a = 0
b = 0
WARNING: redefining constant a
a = 1
WARNING: redefining constant b
b = 0
WARNING: redefining constant a
a = 2
WARNING: redefining constant b
b = 1

c = 0
d = 0
WARNING: redefining constant c
c = 1
WARNING: redefining constant d
d = 1
WARNING: redefining constant c
c = 2
WARNING: redefining constant d
d = 2

Why do the outputs of the two macros differ? Shouldn't it be the same?

And why does julia warn me about the redefinition of b when it doesn't 
really redefine it. (line 5 and 6 of the output)



[julia-users] macro to exclude code depending on VERSION

2015-11-12 Thread andrew cooke

when you're writing code that uses macros, supporting different versions of 
julia seems to be more complex than normal.  in particular, things like:

if VERSION > XX
# code with macros here
end

don't work as expected, because macro expansion occurs before runtime 
evaluation.  so the macros are expenaded whatever version.

given that, i have found this simple macro to be useful;

macro cond(test, block)
if eval(test)
block
end
end

@cond VERSION >= v"0.4" begin
 # code with macros here
end

anyway, my questions are: (1) is the above sensible and (2) does this 
already exist?

thanks,
andrew



Re: [julia-users] macro to exclude code depending on VERSION

2015-11-12 Thread andrew cooke

ah, great.  i won't make a new package then.  thanks.

On Thursday, 12 November 2015 09:30:21 UTC-3, Yichao Yu wrote:
>
> https://github.com/JuliaLang/julia/issues/7449 
> https://github.com/JuliaLang/Compat.jl/pull/131 
> https://github.com/JuliaLang/julia/issues/5892 
>
> On Thu, Nov 12, 2015 at 7:23 AM, andrew cooke  > wrote: 
> > 
> > when you're writing code that uses macros, supporting different versions 
> of 
> > julia seems to be more complex than normal.  in particular, things like: 
> > 
> > if VERSION > XX 
> > # code with macros here 
> > end 
> > 
> > don't work as expected, because macro expansion occurs before runtime 
> > evaluation.  so the macros are expenaded whatever version. 
> > 
> > given that, i have found this simple macro to be useful; 
> > 
> > macro cond(test, block) 
> > if eval(test) 
> > block 
> > end 
> > end 
> > 
> > @cond VERSION >= v"0.4" begin 
> >  # code with macros here 
> > end 
> > 
> > anyway, my questions are: (1) is the above sensible and (2) does this 
> > already exist? 
> > 
> > thanks, 
> > andrew 
> > 
>


Re: [julia-users] macro to exclude code depending on VERSION

2015-11-12 Thread Yichao Yu
https://github.com/JuliaLang/julia/issues/7449
https://github.com/JuliaLang/Compat.jl/pull/131
https://github.com/JuliaLang/julia/issues/5892

On Thu, Nov 12, 2015 at 7:23 AM, andrew cooke  wrote:
>
> when you're writing code that uses macros, supporting different versions of
> julia seems to be more complex than normal.  in particular, things like:
>
> if VERSION > XX
> # code with macros here
> end
>
> don't work as expected, because macro expansion occurs before runtime
> evaluation.  so the macros are expenaded whatever version.
>
> given that, i have found this simple macro to be useful;
>
> macro cond(test, block)
> if eval(test)
> block
> end
> end
>
> @cond VERSION >= v"0.4" begin
>  # code with macros here
> end
>
> anyway, my questions are: (1) is the above sensible and (2) does this
> already exist?
>
> thanks,
> andrew
>


Re: [julia-users] macro to exclude code depending on VERSION

2015-11-12 Thread Seth
...and I just discovered Requires.jl. Fantastic stuff.

On Thursday, November 12, 2015 at 8:55:23 PM UTC-8, Seth wrote:
>
> This could be useful to me :)
>
> I have a couple of functions that require JuMP but I don't want to add 
> JuMP to my REQUIRE file. My usual tactic of checking isdefined(:JuMP) won't 
> work because JuMP uses macros that are evaluated prior to runtime. However, 
> I was unable to make the following code work:
>
> @cond (isdefined(:JuMP)) begin
> function something_that_requires_jump(a...)
> ...
> end # function
> end # macro
>
> Is there an accepted way to do conditional includes of packages that 
> contain macros?
>
> On Thursday, November 12, 2015 at 4:37:43 AM UTC-8, andrew cooke wrote:
>>
>>
>> ah, great.  i won't make a new package then.  thanks.
>>
>> On Thursday, 12 November 2015 09:30:21 UTC-3, Yichao Yu wrote:
>>>
>>> https://github.com/JuliaLang/julia/issues/7449 
>>> https://github.com/JuliaLang/Compat.jl/pull/131 
>>> https://github.com/JuliaLang/julia/issues/5892 
>>>
>>> On Thu, Nov 12, 2015 at 7:23 AM, andrew cooke  
>>> wrote: 
>>> > 
>>> > when you're writing code that uses macros, supporting different 
>>> versions of 
>>> > julia seems to be more complex than normal.  in particular, things 
>>> like: 
>>> > 
>>> > if VERSION > XX 
>>> > # code with macros here 
>>> > end 
>>> > 
>>> > don't work as expected, because macro expansion occurs before runtime 
>>> > evaluation.  so the macros are expenaded whatever version. 
>>> > 
>>> > given that, i have found this simple macro to be useful; 
>>> > 
>>> > macro cond(test, block) 
>>> > if eval(test) 
>>> > block 
>>> > end 
>>> > end 
>>> > 
>>> > @cond VERSION >= v"0.4" begin 
>>> >  # code with macros here 
>>> > end 
>>> > 
>>> > anyway, my questions are: (1) is the above sensible and (2) does this 
>>> > already exist? 
>>> > 
>>> > thanks, 
>>> > andrew 
>>> > 
>>>
>>

Re: [julia-users] macro to exclude code depending on VERSION

2015-11-12 Thread Seth
This could be useful to me :)

I have a couple of functions that require JuMP but I don't want to add JuMP 
to my REQUIRE file. My usual tactic of checking isdefined(:JuMP) won't work 
because JuMP uses macros that are evaluated prior to runtime. However, I 
was unable to make the following code work:

@cond (isdefined(:JuMP)) begin
function something_that_requires_jump(a...)
...
end # function
end # macro

Is there an accepted way to do conditional includes of packages that 
contain macros?

On Thursday, November 12, 2015 at 4:37:43 AM UTC-8, andrew cooke wrote:
>
>
> ah, great.  i won't make a new package then.  thanks.
>
> On Thursday, 12 November 2015 09:30:21 UTC-3, Yichao Yu wrote:
>>
>> https://github.com/JuliaLang/julia/issues/7449 
>> https://github.com/JuliaLang/Compat.jl/pull/131 
>> https://github.com/JuliaLang/julia/issues/5892 
>>
>> On Thu, Nov 12, 2015 at 7:23 AM, andrew cooke  wrote: 
>> > 
>> > when you're writing code that uses macros, supporting different 
>> versions of 
>> > julia seems to be more complex than normal.  in particular, things 
>> like: 
>> > 
>> > if VERSION > XX 
>> > # code with macros here 
>> > end 
>> > 
>> > don't work as expected, because macro expansion occurs before runtime 
>> > evaluation.  so the macros are expenaded whatever version. 
>> > 
>> > given that, i have found this simple macro to be useful; 
>> > 
>> > macro cond(test, block) 
>> > if eval(test) 
>> > block 
>> > end 
>> > end 
>> > 
>> > @cond VERSION >= v"0.4" begin 
>> >  # code with macros here 
>> > end 
>> > 
>> > anyway, my questions are: (1) is the above sensible and (2) does this 
>> > already exist? 
>> > 
>> > thanks, 
>> > andrew 
>> > 
>>
>

Re: [julia-users] Macro definition and call environments

2015-10-15 Thread Stefan Karpinski
On Thu, Oct 15, 2015 at 8:28 AM,  wrote:

> - Do these global variables also refer to function calls like  time(),
> println() within a macro??


Yes, time and println are just const global bindings to generic function
objects.

I am kind of confused how to think of the hygiene of a macro:
>   - Should i be thinking in terms of what is returned as an expr from the
> macro should not conflict with the code context where it is returned?
>   - Or should i be thinking in terms of what is being supplied to macro
> should not conflict with what is inside the macro?


I'm not sure what these two options mean but you should apply `esc()` to
any expressions that should be interpreted as referring to things in the
calling environment. Not sure if that helps.


[julia-users] Macro definition & call environments

2015-10-14 Thread juliatylors
Hi,

can someone explain what macro definition environment and macro call 
environment?

- I was reading the following 
page: 
http://docs.julialang.org/en/release-0.4/manual/metaprogramming/#man-metaprogramming
  - it says in the Hygiene section : 
Local variables are then renamed to be unique (using the gensym() 
 
function, which generates new symbols), and *global variables are resolved 
within the macro definition environment. *


In a later passage:

Thanks.


[julia-users] Macro definition and call environments

2015-10-14 Thread juliatylors
Hi,

can someone explain what macro definition environment and macro call 
environment?

- I was reading the following page: 
http://docs.julialang.org/en/release-0.4/manual/metaprogramming/#man-metaprogramming
  - it says in the Hygiene section : 
"Local variables are then renamed to be unique (using the gensym() 
 function, 
which generates new symbols), and *global variables are resolved within the 
macro definition environment. "*
*  - Do these global variables also refer to function calls like 
 time(), println() within a macro??*


In a later passage:
  - Here the user expression ex is a call to time, but not the same time 
function that the macro uses. It clearly refers to MyModule.time. *Therefore 
we must arrange for the code in **ex to be resolved in the macro call 
environment.*


*I am kind of confused how to think of the hygiene of a macro:*
*  - Should i be thinking in terms of what is returned as an expr from the 
macro should not conflict with the code context where it is returned?*
*  - Or should i be thinking in terms of what is being supplied to macro 
should not conflict with what is inside the macro?*


*Thanks*


[julia-users] Macro to generate function signature

2015-04-30 Thread David Gold
I'm working (in 3.7) on a function that takes two functions f and g as 
inputs, merges all non-conflicting methods of f and g into one function h, 
and returns h. I'm trying to use macros to generate the signatures of each 
method for h:

macro argsgen(typle, n::Int64)
y = eval(:($typle))
xn = symbol(x$n)
return :( $xn :: $(y[n]) )
end

macro repper(typle, n::Int64)
ex = @argsgen($typle, 1)
for i in 2:n
ex = string(ex, , @argsgen($typle, $n))
end

return parse(ex)
end

So, if f has a method with signature (x::Int64), then I can feed the 
1-tuple '(Int64,)' to @argsgen, which generates the proper signature: 

julia ex1 = macroexpand( :(@argsgen((Int64,), 1) ))
:(x1::Int64)

and I can thereby define a method for h:


julia h(@argsgen((Int64,), 1)) = x1 + 1
foobar (generic function with 1 method)

julia h(1)
2

The problem is when I try to do this for a signature of more than one 
argument, say (Int64, Int64). Above I've tried implementing a macro that 
generates an expression of repeated '@argsgen' calls with the appropriate 
second argument:

ex = macroexpand( :( @repper (Int64, Int64) 2 ) )
:((x1::Int64,x2::Int64))

which doesn't quite work when I attempt to use it for a signature:

julia h(@repper (Int64, Int64) 2) = x1 + x2
ERROR: syntax: (x1::Int64,x2::Int64) is not a valid function argument name

How can I get @repper to return an expression that isn't a tuple, but also 
has two @argsgen calls separated by a comma? I've tried a couple of other 
ways of doing this, but each expression wants to be returned as a tuple. 
And I can't find out how to make the tuple splat in such a way that works 
as a signature for h. Any thoughts? (Also, I imagine the tupocalypse will 
break this, but I can deal with that later.) 

Thank you all!
David


Re: [julia-users] Macro to generate function signature

2015-04-30 Thread Isaiah Norton
The reduced case is:

h((x1::Int64,x2::Int64)...) = x1+1

Which doesn't work, because the ... conflicts with the vararg syntax (the
error message is admittedly not very good).

I would suggest to generate the entire function from your macro, in which
case you can just splice the tuple in and everything should work.

ps: using eval inside a macro, and parsing concatenated strings like that,
can and should be avoided. Build Expr objects instead.

On Thu, Apr 30, 2015 at 5:19 PM, David Gold david.gol...@gmail.com wrote:

 I'm working (in 3.7) on a function that takes two functions f and g as
 inputs, merges all non-conflicting methods of f and g into one function h,
 and returns h. I'm trying to use macros to generate the signatures of each
 method for h:

 macro argsgen(typle, n::Int64)
 y = eval(:($typle))
 xn = symbol(x$n)
 return :( $xn :: $(y[n]) )
 end

 macro repper(typle, n::Int64)
 ex = @argsgen($typle, 1)
 for i in 2:n
 ex = string(ex, , @argsgen($typle, $n))
 end

 return parse(ex)
 end

 So, if f has a method with signature (x::Int64), then I can feed the
 1-tuple '(Int64,)' to @argsgen, which generates the proper signature:

 julia ex1 = macroexpand( :(@argsgen((Int64,), 1) ))
 :(x1::Int64)

 and I can thereby define a method for h:


 julia h(@argsgen((Int64,), 1)) = x1 + 1
 foobar (generic function with 1 method)

 julia h(1)
 2

 The problem is when I try to do this for a signature of more than one
 argument, say (Int64, Int64). Above I've tried implementing a macro that
 generates an expression of repeated '@argsgen' calls with the appropriate
 second argument:

 ex = macroexpand( :( @repper (Int64, Int64) 2 ) )
 :((x1::Int64,x2::Int64))

 which doesn't quite work when I attempt to use it for a signature:

 julia h(@repper (Int64, Int64) 2) = x1 + x2
 ERROR: syntax: (x1::Int64,x2::Int64) is not a valid function argument
 name

 How can I get @repper to return an expression that isn't a tuple, but also
 has two @argsgen calls separated by a comma? I've tried a couple of other
 ways of doing this, but each expression wants to be returned as a tuple.
 And I can't find out how to make the tuple splat in such a way that works
 as a signature for h. Any thoughts? (Also, I imagine the tupocalypse will
 break this, but I can deal with that later.)

 Thank you all!
 David



[julia-users] Macro with varargs

2015-04-23 Thread Kuba Roth
This is my first  time writing macros in Julia. I've read related docs but 
could not find an example which works with the arbitrary number of arguments.
So in my example below the args... works correctly with string literals but for 
the passed variables it returns their names and not the values. I'm pretty sure 
this is a newbie mistake and much appreciate any comments.
Thank you.

macro echo (args...)
 :(for x in $args
   print(x,  )
   end)
end

julia @echo AAA VVV 1
AAA VVV 1

julia testB = BBB
BBB
julia testC = CCC
CCC
julia @echo testB testC
testB testC

[julia-users] macro aliases? Can macro have the same assignment like temp = f::Function?

2014-12-31 Thread 良无
I know there are type aliases and function assignment.

I find that a macro call is like Expr(:macrocall, symbol(@time),.)

And we can embed a macro inside a macro, but it looks really uncomfortable 
to me.

Thanks.


[julia-users] Macro scoping (or hygiene?) problems

2014-12-30 Thread Tomas Lycken


I’m doing some metaprogramming for Interpolations.jl, and I’m getting stuck 
at an error that I think is due to scoping issues in my nested quotes, and 
I’ve stared at this for so long now I’m not getting anywhere.

I can do the following

matching(d) = quote
println(Matching: , $d)
end

nonmatching(d) = quote
println(Not matching: , $d)
end

@ngenerate N T function example{T,N}(A::Array{T,N}, xs::NTuple{N,Real}...)
@nexprs N dim-begin
@nexprs N d-begin
if d==dim
eval(matching(d))
else
eval(nonmatching(d))
end
end
end
end

example(rand(2,2), 1.5, 0.7)

and get the expected output:

Matching: 1
Not matching: 2
Not matching: 1
Matching: 2

Examining with macroexpand, I see that the eval calls are still there, but 
for performance reasons I want to avoid them, so I try to rewrite it to use 
eval(ngenerate(...)) instead of @ngenerate ...:

#matching and nonmatching defined as before

ex = ngenerate(
:N,
:T,
:(example{T,N}(A::Array{T,N}, xs::NTuple{N,Real}...)),
N-quote
@nexprs $N dim-begin
@nexprs $N d-begin
if d==dim
$(matching(d))
else
$(notmatching(d))
end
end
end
end
)

eval(ex)

example(rand(2,2), 1.5, 0.7)

But this doesn’t work: I get ERROR: d not defined on $(matching(d)) (and, 
if I comment that one out, $(nonmatching(d))). I’ve tried $(matching($d)) 
(ERROR: 
error compiling anonymous: syntax: prefix $ in non-quoted expression) as 
well as $(matching(esc(d))) and $(esc(matching(d))) (both ERROR: d not 
defined), and I’m at a loss for what to try (these errors are all thrown at 
the stage of *defining* the quoted expression, so macroexpand hasn’t helped 
me here either, as I don’t get any expression to call it on…).

Eventually, this will be used to do different things for different array 
dimensions like here, but with both matching and nonmatching also 
dispatching on types of some additional arguments that I left out for 
simplicity, and choosing expressions by means of multiple dispatch this way 
is really at the core of Interpolations.jl, so I can’t move the contents of 
matching and nonmatching out of their respective functions.

Thanks in advance for any ideas that get me forward,

// Tomas
​


[julia-users] macro expansion for @until

2014-09-14 Thread Zouhair Mahboubi
New Julia user here :)

Following the scipy/julia tutorial by D. Sanders and playing around with 
Macros 
http://nbviewer.ipython.org/github/dpsanders/scipy_2014_julia/blob/master/Metaprogramming.ipynb

He has in there an example of macros. I was playing around with that and I 
ran into a case where I don't understand why the expanded code ends up 
introducing what seems to be a local variable. And this depends solely on 
whether `expr2` contains `i += 1` or `i = i + 1`.

Can someone take the time to explain why i one case the macro expansion 
introduces a local variable? And how would one get around that in this case?

Thanks,
-z


In [111]:

macro until(expr1, expr2)

quote

#:(

while !($expr1)  # code interpolation

$expr2

end

#)

end

end

 

In [122]:

expr1 = 

quote

i = 0

@until i==10 begin

print(i)

i += 1

end

end;

expr2 = 

quote

i = 0

@until i==10 begin

print(i)

i = i + 1

end

end;

In [123]:

eval(expr1)

0123456789

In [124]:

eval(expr2)

i not defined
while loading In[124], in expression starting on line 1

 in anonymous at In[122]:4


In [125]:

macroexpand(expr1)

Out[125]:

quote  # In[122], line 3:
i = 0 # line 4:
begin  # In[111], line 4:
while !(i == 10) # line 5:
begin  # In[122], line 5:
print(i) # line 6:
i += 1
end
end
end
end

In [126]:

macroexpand(expr2)

Out[126]:

quote  # In[122], line 11:
i = 0 # line 12:
begin  # In[111], line 4:
while !(#3677#i == 10) # line 5:
begin  # In[122], line 13:
print(#3677#i) # line 14:
#3677#i = #3677#i + 1
end
end
end
end



Re: [julia-users] macro expansion for @until

2014-09-14 Thread Stefan Karpinski
You need to call esc on the expressions to provide macro hygiene. Sorry for
the brief reply, but let me know if that helps. Btw, did you mean to
include output from macroexpand above? If so, it doesn't seem to have
gotten included.

On Sun, Sep 14, 2014 at 9:28 PM, Zouhair Mahboubi 
zouhair.mahbo...@gmail.com wrote:

 New Julia user here :)

 Following the scipy/julia tutorial by D. Sanders and playing around with
 Macros
 http://nbviewer.ipython.org/github/dpsanders/scipy_2014_julia/blob/master/Metaprogramming.ipynb

 He has in there an example of macros. I was playing around with that and I
 ran into a case where I don't understand why the expanded code ends up
 introducing what seems to be a local variable. And this depends solely on
 whether `expr2` contains `i += 1` or `i = i + 1`.

 Can someone take the time to explain why i one case the macro expansion
 introduces a local variable? And how would one get around that in this case?

 Thanks,
 -z


 In [111]:

 macro until(expr1, expr2)

 quote

 #:(

 while !($expr1)  # code interpolation

 $expr2

 end

 #)

 end

 end



 In [122]:

 expr1 =

 quote

 i = 0

 @until i==10 begin

 print(i)

 i += 1

 end

 end;

 expr2 =

 quote

 i = 0

 @until i==10 begin

 print(i)

 i = i + 1

 end

 end;

 In [123]:

 eval(expr1)

 0123456789

 In [124]:

 eval(expr2)

 i not defined
 while loading In[124], in expression starting on line 1

  in anonymous at In[122]:4


 In [125]:

 macroexpand(expr1)

 Out[125]:

 quote  # In[122], line 3:
 i = 0 # line 4:
 begin  # In[111], line 4:
 while !(i == 10) # line 5:
 begin  # In[122], line 5:
 print(i) # line 6:
 i += 1
 end
 end
 end
 end

 In [126]:

 macroexpand(expr2)

 Out[126]:

 quote  # In[122], line 11:
 i = 0 # line 12:
 begin  # In[111], line 4:
 while !(#3677#i == 10) # line 5:
 begin  # In[122], line 13:
 print(#3677#i) # line 14:
 #3677#i = #3677#i + 1
 end
 end
 end
 end




[julia-users] macro for generating functions with optional arguments

2014-05-08 Thread Kevin Squire
In your example, nothing is of type Nothing, which is not a MyType, so the
assignment fails.

Tim, for kw arguments, is it true that new functions are specialized for
each type?  I'm thought that it wouldn't, which would cause the variable to
be an actual Union type if declared as such, and therefore not as
efficient. I'll test this when I get to a computer.

Cheers,
   Kevin

On Thursday, May 8, 2014, Adam Smith
swiss.army.engin...@gmail.comjavascript:_e(%7B%7D,'cvml','swiss.army.engin...@gmail.com');
wrote:

 That doesn't seem to work with composite types and Nothing. Using a
 day-old nightly build:

 julia type MyType; end

 julia example(x::Int, mt::MyType=nothing) = println(in example)
 example (generic function with 2 methods)

 julia example(1)
 ERROR: no method example(Int64, Nothing)
  in example at none:1

 julia example(1, MyType())
 in example

 Which is why I resorted to the Union() stuff.


 On Thursday, May 8, 2014 10:32:10 AM UTC-4, Tim Holy wrote:

 I agree that declaring types is an effective way of increasing clarity.
 (Fundamentally I suspect that suggests inadequacies in our documentation.)
 Aside from the more valid use in controlling which version of a function
 will run on which types of data.

 However, you don't have to leave off type information from optional
 arguments:

 function findsmallest(v::Vector, issorted::Bool = false)
 if issorted
 return v[1]
 else
 return minimum(v)
 end
 end

 will be callable either as findsmallest(v, false) or findsmallest(v). If
 you do
 supply the extra argument, it must be a Bool. Doesn't that do what you're
 hoping for?


 You can also supply types to keyword arguments, i.e.,

 function findsmallest(v::Vector; issorted::Bool = false)

 which will then be callable either as findsmallest(v) or findsmallest(v,
 issorted=true).

 --Tim

 On Thursday, May 08, 2014 07:00:42 AM Adam Smith wrote:
  That makes sense. The other (primary) reason I want this is still valid:
  assisting multiple dispatch (and clarity for other developers) by having
  the correct types on optional arguments. Since there are no objects for
  encapsulation of related behaviors, the only good way to explore an API
  (other than just reading its source) is to use Julia's reflection
 utilities
  like names() and methods(). I want to be able to use brief function
 names
  like add!() on my types, but if every optional argument requires
 leaving
  off the type information, there will quickly be ambiguity/collisions
 with
  the definitions in different places. Since each one is really intended
 for
  a specific type, having that in the function signature would improve
  clarity quite a bit. That's why I spent a bit of time trying to
 construct
  the @optional macro.
 
  On Thursday, May 8, 2014 9:18:01 AM UTC-4, Tim Holy wrote:
   I'm not sure I understand. Except for one particular situation (tuple
   arguments), declaring the type of inputs has no impact on performance.
 The
   JIT
   will compile a separate version of the function for each different set
 of
   input
   types. See the performance tips section of the manual.
  
   --Tim
  
   On Thursday, May 08, 2014 01:34:12 AM Adam Smith wrote:
Actually performance is one of the reasons I wanted to do it this
 way,
rather than leaving off type info and just dealing with Anys, which
 is
slower (and makes multiple dispatch very messy). I will read through
Julia's parser a bit more and then file an issue.
   
 a d a m
   
On May 8, 2014, at 1:25 AM, Kevin Squire
kevin@gmail.comjavascript:
   wrote:
 Hi Adam,

 While working with optional and union types won't be as performant
 as
 regular types, this seems like it would be useful.  Why don't you
 file
  
   an
  
 issue?  It might not be easy or feasible to do what you want, but
 it's
 good to bring it to the attention of the main devs.

 Cheers,

Kevin

 On Wed, May 7, 2014 at 5:15 PM, Adam Smith
  
 swiss.arm...@gmail.com javascript: wrote:
Did you make any progress on
  
 this? I tried to do the exact same thing as you, got the exact
 same
 error, googled, and found this post. It seems that Julia parses
  
   default
  
 values for arguments separately from the name/type of the
 arguments.
 This was the macro I attempted:
 macro optional(name, ptype)

 esc(:($name::Union(Nothing, $ptype) = nothing))

 end

 With the desired usage being:
 function do_stuff(x::Int, y::String, @optional(z, Float))

 # do stuff





[julia-users] Macro leads to slow code(?!)

2014-03-15 Thread andrew cooke

i have no idea what is happening here.  please can someone explain why 
these give such different results?  thanks, andrew

 cat Memory.jl

immutable Fast{U:Unsigned} 
i::U
end
+{U:Unsigned}(a::Fast{U}, b::Fast{U}) = Fast{U}(a.i $ b.i)

immutable Slow{I:Unsigned}  
i::I
end
for (name, op) in ((:+, $),)
@eval $name{U:Unsigned}(a::Slow{U}, b::Slow{U}) = Slow{U}($op(a.i, b.i
))
end

 julia
   _
   _   _ _(_)_ |  A fresh approach to technical computing
  (_) | (_) (_)|  Documentation: http://docs.julialang.org
   _ _   _| |_  __ _   |  Type help() to list help topics
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 0.3.0-prerelease+1998 (2014-03-13 01:20 
UTC)
 _/ |\__'_|_|_|\__'_|  |  Commit 9e0e3bd* (2 days old master)
|__/   |  x86_64-suse-linux

julia using Memory
Warning: requiring Memory did not define a corresponding module.

julia code_native(+, (Fast{Uint8}, Fast{Uint8}))
.text
Filename: /home/andrew/.julia/v0.3/IntModN/src/Memory.jl
Source line: 5
pushRBP
mov RBP, RSP
xor EDI, ESI
Source line: 5
mov AL, DIL
pop RBP
ret

julia code_native(+, (Slow{Uint8}, Slow{Uint8}))
.text
Filename: /home/andrew/.julia/v0.3/IntModN/src/Memory.jl
Source line: 11
pushRBP
mov RBP, RSP
pushRBX
sub RSP, 40
mov QWORD PTR [RBP - 40], 4
Source line: 11
movabs  RBX, 139916932623568
mov RAX, QWORD PTR [RBX]
mov QWORD PTR [RBP - 32], RAX
lea RAX, QWORD PTR [RBP - 40]
mov QWORD PTR [RBX], RAX
mov QWORD PTR [RBP - 16], 0
Source line: 11
mov QWORD PTR [RBP - 24], 13308928
movabs  RAX, 139916939396576
callRAX
movabs  RCX, 139916917454832
movzx   EDI, AL
callRCX
Source line: 11
lea RSI, QWORD PTR [RBP - 24]
Source line: 11
movabs  RCX, 139916917189328
mov QWORD PTR [RBP - 16], RAX
mov EDI, 29726432
mov EDX, 2
callRCX
mov AL, BYTE PTR [RAX + 8]
mov RCX, QWORD PTR [RBP - 32]
mov QWORD PTR [RBX], RCX
add RSP, 40
pop RBX
pop RBP
ret