Enjoy:
julia> macro n(expr::Expr)
@assert expr.head == :function
s = expr.args[1].args[2]
if isa(s,Expr) && s.head == :(::)
s = s.args[1]
end
unshift!(expr.args[2].args, :(n = length($s)))
esc(expr)
end
julia> macroexpand(:( @n function f(x,y)
println("length of x is $n")
end))
:(function f(x,y)
n = length(x) # none, line 2:
println("length of x is $(n)")
end)
julia> @n function f(x,y)
println("length of x is $n")
end
f (generic function with 1 method
julia> @n function f(x::Vector{Int},y)
println("INTVEC: length of x is $n")
end
f (generic function with 2 methods)
julia> f(rand(4),rand(5))
length of x is 4
julia> f(rand(Int,4),rand(5))
INTVEC: length of x is 4
On Wed, Feb 24, 2016 at 9:03 AM, Alex <[email protected]> wrote:
> Hi everybody,
>
> I have several functions operating on one dimensional vectors.
>
> Within each function the first thing I do is to define variable n holding
> the length of input vector x:
>
> n = length(x)
>
> Is that possible to factor out this pattern somehow from all functions
> definitions?
>
> (...like 'traits' in Scala)
>
> I mean, to make variable n automatically defined as a length of the first
> argument (which is always a one dimensional vector) of each function?
>
>
>