Julia 中的单项式向量

Tio*_*ias 3 julia

假设你有一个向量a元组$a$,我想在julia中定义一个函数p(x)=x^a。

例如,如果 a=(1,2,3),则所得函数将为 x^1 *y^2 * z^3。

我希望有一个适用于任何元组的通用方法,但我不知道适当的符号。在我的代码中,我有一个元组数组,我想为数组中的每个元组定义一个单项式。

非常感谢您的合作。

Bog*_*ski 5

这是你想要的吗?

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
Run Code Online (Sandbox Code Playgroud)