Skip to content

Instantly share code, notes, and snippets.

@oschulz
Created November 2, 2024 15:10
Show Gist options
  • Select an option

  • Save oschulz/d576a377899a798675de1c85eb2a1f8f to your computer and use it in GitHub Desktop.

Select an option

Save oschulz/d576a377899a798675de1c85eb2a1f8f to your computer and use it in GitHub Desktop.
abstract type Countable{sym} end
Base.show(io::IO, x::Countable{sym}) where sym = print(io, x.n == 1 ? "$sym" : "$(x.n)$sym")
getsym(x::Countable{sym}) where sym = sym
Base.:*(n::Integer, x::Countable) = typeof(x)(n * x.n)
Base.:+(a::Countable, b::Countable) = error("Can't add $(getsym(a))s and $((getsym(b)))s")
Base.:+(a::T, b::T) where {T<:Countable} = T(a.n + b.n)
Base.:<(a::Countable, b::Countable) = error("Can't compare $(getsym(a))s with $(getsym(b))s")
Base.:<(a::T, b::T) where {T<:Countable} = a.n < b.n
struct Fruit{sym} <: Countable{sym}
n::Int
end
struct Animals{sym} <: Countable{sym}
n::Int
end
Base.:+(eaters::Animals, fruit::Fruit) = typeof(fruit)(fruit.n - eaters.n)
const ๐ŸŽ = Fruit{:๐ŸŽ}(1)
const ๐Ÿ = Fruit{:๐Ÿ}(1)
const ๐ŸŒ = Fruit{:๐ŸŒ}(1)
const ๐Ÿ˜ฎ = Animals{:๐Ÿ˜ฎ}(1)
const ๐Ÿ’ = Animals{:๐Ÿ’}(1)
const ๐Ÿ„ = Animals{:๐Ÿ„}(1)
Base.:+(eaters::Animals{:๐Ÿ’}, fruit::Fruit{:๐ŸŒ}) = typeof(fruit)(fruit.n - 2 * eaters.n)
function Base.:+(eaters::Animals{:๐Ÿ„}, fruit::Fruit)
@warn "Moooooo!"
return fruit
end
typeof(๐ŸŽ) == typeof(๐Ÿ)
๐ŸŽ + 2๐ŸŽ + 3๐ŸŽ
2๐ŸŽ < 3๐ŸŽ
2๐ŸŽ + 3๐Ÿ
๐ŸŽ < ๐Ÿ
4๐Ÿ˜ฎ + 6๐ŸŽ
2๐Ÿ˜ฎ + 6๐ŸŒ
2๐Ÿ’ + 6๐ŸŒ
2๐Ÿ„ + 6๐ŸŒ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment