朱莉娅的半环矢量产品不起作用

时间:2018-04-30 19:27:48

标签: julia

我正在尝试在Julia(0.6.2)中实现max-plus半环代数,继本文之后:

http://www.mit.edu/~kepner/pubs/JuliaSemiring_HPEC2013_Paper.pdf

直接从上述文件中得出的max-plus数字的类型定义和所有相关运算符的定义如下:

# define max-plus number type

immutable MPNumber{T} <: Number 
  val::T
end

+(a::MPNumber, b::MPNumber) = MPNumber(max(a.val, b.val))

*(a::MPNumber, b::MPNumber) = MPNumber(a.val + b.val)

show(io::IO, k::MPNumber) = show(io, k.val)

zero{T}(::MPNumber{T}) = MPNumber(typemin(T))

one{T}(::MPNumber{T}) = MPNumber(zero(T))

promote_rule{T<:Number}(::Type{MPNumber}, ::Type{T}) = MPNumber

mparray(A::Array) = map(MPNumber, A)

array{T}(A::Array{MPNumber{T}}) = map(x->x.val, A)

max-plus加法和乘法的基本测试工作很好,例如

MPNumber(1) + MPNumber(1)
正如预期的那样,

给出MPNumber(1)。如文中所示,Max-plus矩阵取幂也像魅力一样:

A = mparray(Array([[1, 2] [3, 4]]))
A*A

给出

2×2 Array{MPNumber{Int64},2}:
 MPNumber{Int64}(5)  MPNumber{Int64}(7)
 MPNumber{Int64}(6)  MPNumber{Int64}(8)

然而,当我尝试将max-plus向量与max-plus矩阵相乘时,

A = mparray(Array([[1, 2] [3, 4]]))
x = mparray([1, 2])

A*x

我收到以下错误:

MethodError: Cannot `convert` an object of type Int64 to an object of type MPNumber{Int64}
This may have arisen from a call to the constructor MPNumber{Int64}(...) since type constructors fall back to convert methods.

Stacktrace:
 [1] generic_matvecmul!(::Array{MPNumber{Int64},1}, ::Char, ::Array{MPNumber{Int64},2}, ::Array{MPNumber{Int64},1}) at ./linalg/matmul.jl:434
 [2] Ac_mul_B(::Array{MPNumber{Int64},1}, ::Array{MPNumber{Int64},2}) at ./linalg/rowvector.jl:227

我还是朱莉娅的新手,所以我很难弄清楚这里出了什么问题以及如何修复它。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:7)

这是在Julia 0.6.2下测试的。 使用以下代码:

public interface IMessageManager
{
    void AddSuccess(string message, int? dismissAfter = null);
    void AddError(string message, int? dismissAfter = null);
    void AddInfo(string message, int? dismissAfter = null);
    void AddWarning(string message, int? dismissAfter = null);
    Dictionary<string, IEnumerable<FlashMessage>> GetAlerts();
}

(我建议您从这部分开始,因为转换和促销更加棘手,不需要用于您的目的)。

注意到关键部分是我通过在struct MPNumber{T} <: Number val::T end Base.:+(a::MPNumber, b::MPNumber) = MPNumber(max(a.val, b.val)) Base.:*(a::MPNumber, b::MPNumber) = MPNumber(a.val + b.val) Base.show(io::IO, k::MPNumber) = show(io, k.val) Base.zero(::MPNumber{T}) where T = MPNumber(typemin(T)) Base.one(::MPNumber{T}) where T = MPNumber(zero(T)) Base.zero(::Type{MPNumber{T}}) where T = MPNumber(typemin(T)) Base.one(::Type{MPNumber{T}}) where T = MPNumber(zero(T)) mparray(A::Array) = map(MPNumber, A) 前面加Base来扩展函数。对于Base.+,您需要在函数名称之前另外使用*

现在你可以运行你想要的一切:

:

希望。

编辑:我在您的代码中对julia> MPNumber(1) + MPNumber(1) 1 julia> A = mparray(Array([[1, 2] [3, 4]])) 2×2 Array{MPNumber{Int64},2}: 1 3 2 4 julia> A*A 2×2 Array{MPNumber{Int64},2}: 5 7 6 8 julia> A = mparray(Array([[1, 2] [3, 4]])) 2×2 Array{MPNumber{Int64},2}: 1 3 2 4 julia> x = mparray([1, 2]) 2-element Array{MPNumber{Int64},1}: 1 2 julia> A*x 2-element Array{MPNumber{Int64},1}: 5 6 zero定义做了更完整的规定,并遵循标准要求。