Wrapper Types

I am rebuilding my framework (recommender systems).
I’m thinking about a new modeling of the problem and I’m testing some things.
However, I was left with some doubts and I did not find a solution here.

I created a wrapper for the integer and it will be my identifier.
I would like to call functions using integers and would not like to be converting it.

Is it possible to do this?


module Persa

# package code goes here
import Base: convert, promote_rule

struct ID

struct Rating{T <: Number}

Base.promote_rule(::Type{ID}, ::Type{Int}) = ID
Base.convert(::Type{Persa.ID}, x::Int) = Persa.ID(x)
end # module

When I call this function, Julia don´t convert my type automatically.

rating = Persa.Rating(Persa.ID(1), 2, 5)


The problem here seems to be with the type parameter T in struct Rating{T <: Number}.
Because the existence of T, Persa.Rating includes everything like Persa.Rating{Int}, Persa.Rating{Float64}, etc.
So Julia doesn’t know which one is the target type of Persa.Rating(x), and it won’t use implicit conversion at all.
And if we give information for T, things will be okay, for example:

rating = Persa.Rating{Int}(Persa.ID(1), 2, 5)
rating = Persa.Rating{Float64}(Persa.ID(1), 2, 5)

1 Like

It worked here. Makes sense.

I’ve tried here to write an extra constructor, but it did not work either.
The function did not remove the ambiguity.

Rating(user::ID, item::ID, value::T) where T <: Number = Rating{T}(user, item, value)

I think I’m going to give up this path and put directly as an integer.

Thank you!

Rating(user, item, value::T) where T <: Number = Rating{T}(user, item, value)
should work.
So julia knows to get T from the type of value.

So, It don’t work too.
The error message is completely empty.

Error: StackOverFlowError:

Works! Thanks!
The error appears when you set it this way:
Rating(user, item, value::T) where T <: Number = Rating(user, item, value)

However, this behavior is very strange.

The stack overflow error is because the method definition Rating(user, item, value::T) where T <: Number = Rating(user, item, value) is really a circular one, the RHS is of the form of LHS.

1 Like

Yes, after reviewing I realized.

However, the error message did not help.