我正在尝试在 Julia 中创建一个复合类型来表示椭圆曲线上的点。 如果满足 y^2 == x^3 + a*x + b 或 x 和 y 都不等于任何值,则点有效。请注意,后一种情况代表无穷远点。
我想出了下面的代码,但无法弄清楚如何解释无穷远点。
- 有没有办法处理结构体中的不同异常?
- 异常可以简单地返回有效类型而不是错误吗?例如如果 x == 无 && y == 无则 Point(无,无,a,b)
IntOrNothing = Union{Int,Nothing}
struct Point
x::IntOrNothing
y::IntOrNothing
a::Int
b::Int
Point(x,y,a,b) = x == nothing || y == nothing || y^2 != x^3 + a*x + b ? error("Point is not on curve") : new(x,y,a,b)
end
最佳答案
我会为Point
定义两个内部构造函数,如下所示:
IntOrNothing = Union{Int,Nothing}
struct Point
x::IntOrNothing
y::IntOrNothing
a::Int
b::Int
Point(x::Nothing,y::Nothing,a,b) = new(x,y,a,b)
Point(x,y,a,b) = y^2 != x^3 + a*x + b ? error("Point is not on curve") : new(x,y,a,b)
end
因为我认为这最具可读性。
请注意,如果您调用 Point(nothing,2,1,3)
,您将得到 MethodError
但我猜从您的代码中您不关心的类型只要是无效数据就抛出异常。
它能解决您的问题吗?
关于julia - 如何在 Julia 的复合类型中指定条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52782146/