Enum or struct?

I would have chosen 1 but finance packages I’ve seen do something like 2.
Is this better Julia ? more functional ?

Option 1 - using enum

@enum DayCount  Actual360   Actual365 

Year_Fraction(d1::Date,d2::Date,dc::DayCount) =   
    @Match.match dc begin
        Actual360 => (d2 - d1)/Days(360)
        Actual365 => (d2 - d1)/Days(365)

Option 2 - using types

abstract type Day_Count end

struct Actual_360 <: Day_Count end
struct Actual_365 <: Day_Count end

Year_Fraction(d1::Date,d2::Date, ::Actual_360) = (d2 - d1)/Day(360)
Year_Fraction(d1::Date,d2::Date, ::Actual_365) = (d2 - d1)/Day(365)

When we type

julia> @macroexpand @enum DayCount  Actual360   Actual365

in REPL, we can see that a primitive type is created:

primitive type DayCount <: Base.Enums.Enum{Int32} 32 end

and a dictionary related

 Dict{Int32, Symbol}(0 => :Actual360, 1 => :Actual365)

and at the end, it is still about the types. It seems Option 2 has less computation overhead.

1 Like

While enum’s use types, they are still pretty different than the 2nd option. The first option is making a single (primitive) type representing all Day_Count’s, and then using two values of that type to represent different counts. The 2nd option is making separate types for each Day_Count.

One way to see the difference is: do you want the compiler to specialize on which Day_Count it is? And do you want type instability if it cannot infer which Day_Count it is? Both of those correspond to the 2nd option, since it is using separate types to represent the counts. Whether or not it is a good option depends on how it will be used.


In reality there are 10 or so Day-Count types. I believe they are only used in a Year-Fraction function like the one shown.

I guess with Option 2 (as a struct) you can use a match statement or a method for each type. Whereas Option 1 limits you to the match statement.

As Professor Mehmet says Option 2 has less overhead.

enums have the advantage, when importing data from CSV, a string can be converted to an enum via |> Symbol |> eval. Its not so easy with struct types.

1 Like