name = :hi
vectype = Vector{Int}
quote
function ($name)(v::$vectype)
println("hi")
end
end
macro customFun(vectype::DataType, name::Symbol)
quote
function ($name)(v::$vectype)
println("hi World!")
end
end
end
@customFun(Vector{Int}, :hi)
julia> function customFun(vectype::DataType, name::Symbol) @eval function ($name)(v::$vectype) println("hello world") end endcustomFun (generic function with 1 method)
julia> customFun(Vector{Int},:hi)hi (generic function with 1 method)
julia> hi(rand(Int, 5))hello world
julia> methods(hi)# 1 method for generic function "hi":hi(v::Array{Int64,1}) at none:3
f{T}(vectype:T) = <do something useful with the T>
f{T<:FloatingPoint}(v::Vector{T}) = <something for floats>
f{T<:Integer}(v::Vector{T}) = <something for ints>
julia> macro customFun(vectype::Expr, name::Symbol) quote function $(esc(name))(v::$(esc(vectype))) println(typeof(v)) end end end
julia> @customFun Vector{Int} ff (generic function with 1 method)
julia> f(Int[])Array{Int64,1}
function sort!(v::AbstractVector, f, lo::Int=1, hi::Int=length(v))
@inbounds for i = lo+1:hi
j = i
x = v[i]
while j > lo
if f(x, v[j-1])
v[j] = v[j-1]
j -= 1
continue
end
break
end
v[j] = x
end
return v
end
# Some type
immutable CompType
a::Int
b::Int
c::Int
end
b = [CompType(1,2,3), CompType(3,2,1), CompType(2,1,3)]
# Functors
immutable AFunc end
call(::AFunc, x, y) = x.a < y.a
immutable BFunc end
call(::BFunc, x, y) = x.b < y.b
immutable CFunc end
call(::CFunc, x, y) = x.c < y.c
# Can now sort with good performance
sort!(b, AFunc())
println(b)
sort!(b, BFunc())
println(b)
sort!(b, CFunc())
println(b)lt(o::ForwardOrdering, a, b) = isless(a,b) lt(o::ReverseOrdering, a, b) = lt(o.fwd,b,a)