Hi all,

I was wondering if this is a julian use of the @generated macro:

type Functor{Symbol} end

# A simple general product-sum operator;
# returns a[1]⊙b[1] ⊕ a[2]⊙b[2] ⊕ ...
@generated function dot{⊕,⊙,T}(::Type{Functor{⊕}}, ::Type{Functor{⊙}}, 
a::Array{T}, b::Array{T})
    return quote
        assert(length(a)==length(b))
        p = zero(T)
        for i=1:length(a)
            @inbounds p=$⊕(p,$⊙(a[i],b[i]))
        end
        p
    end
end

The idea is to produce a specialized dot() operator that can work with 
arbitrary product and sum operators yet still be computationally efficient. 
These are some examples on how to use the above function:

dot(Functor{:+},   Functor{:*}, [-1,0,1],[1,0,1])  # vector dot; returns 0
dot(Functor{:max}, Functor{:+}, [-1,0,1],[1,0,1])  # max-sum; returns 2
dot(Functor{:|},   Functor{:&}, [true,false,true],[false,true,true])  # 
constraint satisfaction; returns true

Testing shows that this is faster by about 10x than passing the functions 
directly and runs at the same speed . It also doesn't go through any memory 
allocations.

Reply via email to