[英]How to specify conditions within Julia's composite types?
我正在嘗試在Julia中創建表示橢圓曲線上點的復合類型。 如果滿足y ^ 2 == x ^ 3 + a * x + b或x和y都等於零,則點有效。 注意,后一種情況表示無窮遠處的點。
我想出了以下代碼,但無法弄清楚如何計算無窮大點。
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
Point(nothing,2,1,3)
但是我想從您的代碼中您並不關心拋出的異常的類型,只要將異常拋出到無效數據上即可。
它能解決您的問題嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.