Using the SimpleTraits.jl package

The SimpleTraits.jl package (https://github.com/mauro3/SimpleTraits.jl) may be used to make programming traits a little easier.

Let's try to redo the LiquidityStyle example using SimpleTraits. First, define a trait called IsLiquid, as follows:

@traitdef IsLiquid{T}

The syntax may look a little awkward since the T seems to be doing nothing, but it is actually required because the trait is applicable for a specific type T. The next thing is to assign types to this trait:

@traitimpl IsLiquid{Cash}
@traitimpl IsLiquid{Investment}

Then, a special syntax with four colons can be used to define functions that take objects exhibiting the trait:

@traitfn marketprice(x::::IsLiquid) = error("Please implement pricing function for ", typeof(x))
@traitfn marketprice(x::::(!IsLiquid)) = error("Price for illiquid asset $x is not available.")

The positive case has the argument annotated with x::::IsLiquid, while the negative case has the argument annotated with x::::(!IsLiquid). Note that the parentheses is required so that the code can be parsed correctly. Now, we can test the functions as follows:

As expected, both default implementations throw an error. Now, we can implement the pricing function for Stock and quickly test again:

Looks great! As we can see, the SimpleTrait.jl package simplifies the process of creating traits.

Using traits can make your code more extendable. We must keep in mind, however, that it takes some effort to design proper traits. Documentation is also important so that anyone who wants to extend the code can understand how to utilize the predefined traits.

Next, we will go over parametric types, which are commonly used to extends data types easily.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.152.162