Reputation: 495
Suppose that you have a vector a tuple $a$, I want to define a function p(x)=x^a in julia.
For example, if a=(1,2,3), the resultant function would be x^1 *y^2 * z^3.
I would like to have a general method for any tuple, however I don't know the appropiate notation. In my code, I have an array of tuples and I want to define a monomial for each tuple in the array.
Thank you very much for your collaboration.
Upvotes: 3
Views: 85
Reputation: 69949
Is this what you want?
julia> function genmonomial(t::Tuple{Vararg{Integer}})
@assert !isempty(t) && all(>=(0), t)
return (x...) -> begin
@assert length(x) == length(t)
return mapreduce(x -> x[1]^x[2], *, zip(x, t))
end
end
genmonomial (generic function with 1 method)
julia> f = genmonomial((2,3,4))
#1 (generic function with 1 method)
julia> f(2, 1, 1)
4
julia> f(1, 2, 1)
8
julia> f(1, 1, 2)
16
julia> f(2, 2, 2)
512
julia> f(1, 1)
ERROR: AssertionError: length(x) == length(t)
julia> genmonomial(())
ERROR: AssertionError: !(isempty(t)) && all((>=)(0), t)
julia> genmonomial((1.5,))
ERROR: MethodError: no method matching genmonomial(::Tuple{Float64})
Closest candidates are:
genmonomial(::Tuple{Vararg{Integer}}) at REPL[1]:1
Upvotes: 5