Skip to content

Instantly share code, notes, and snippets.

@tk3369
Created March 12, 2019 06:58
Show Gist options
  • Save tk3369/c52c4dc2e6f562d959743ddfd7d9f7fd to your computer and use it in GitHub Desktop.
Save tk3369/c52c4dc2e6f562d959743ddfd7d9f7fd to your computer and use it in GitHub Desktop.
promote_rule example
julia> import Base: promote_rule, convert
julia> struct USD
value
end
julia> struct Painting
rating
end
julia> promote_rule(::Type{USD}, ::Type{Painting}) = USD
promote_rule (generic function with 138 methods)
julia> promote_type(Painting, USD)
USD
julia> convert(::Type{USD}, p::Painting) = USD(p.rating * 1000)
convert (generic function with 187 methods)
julia> mona_lisa = Painting(250)
Painting(250)
julia> grab(x::USD, y::USD) = USD(x.value + y.value)
grab (generic function with 2 methods)
julia> grab(x::USD, y::Painting) = grab(promote(x, y)...)
grab (generic function with 2 methods)
julia> grab(USD(100), mona_lisa)
USD(250100)
julia> grab(x::Painting, y::USD) = grab(promote(x, y)...)
grab (generic function with 4 methods)
julia> grab(mona_lisa, USD(100))
USD(250100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment