简体   繁体   中英

How to specify conditions within Julia's composite types?

I am trying to create a composite type in Julia representing points on an elliptic curve. Point are valid if satisfying y^2 == x^3 + a*x + b OR both x and y are equal to nothing. Note that the later case represents point at infinity.

I have come up with the below code but can't figure out how to account for point at infinity.

  • Is there a way to handle different exceptions in struct?
  • Can exception simply return a valid type instead of an error? eg if x == nothing && y == nothing then Point(nothing,nothing,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

I would define two inner constructors for Point like this:

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

as this would be most readable in my opinion.

Note that you will get MethodError if you call Point(nothing,2,1,3) but I guess from your code you do not care about the type of exception thrown as long as it is thrown on invalid data.

Does it solve your problem?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM