I’m creating a package to run Black Jack simulations.
I would like to write structs A
, C2
(2-card), … etc for each card type in a deck. And, to have a general Card
struct, so I can overload methods like +, ==, with Card
logic that permeates to every card.
So far, I tried some things, and ended up with problems:
export A, C2, C3, C4, C5, C6, C7, C8, C9, C10, CJ, Card, Deck, NewDeck, Hand, isA, isTens, is2_6, CountPositive, CountNegative, CardType
struct Card
Symbol::String
Value::Vector{Int}
end
# Define a parametric struct for card types
struct CardType{T<:Card}
card::T
end
@generated function ≂(x, y)
if !isempty(fieldnames(x)) && x == y
mapreduce(n -> :(x.$n ≂ y.$n), (a,b)->:($a && $b), fieldnames(x))
else
:(x == y)
end
end
function ==(a::T, b::T) where T <: CardType
if !isempty(fieldnames(x)) && x == y
mapreduce(n -> :(x.$n ≂ y.$n), (a,b)->:($a && $b), fieldnames(x))
else
:(x == y)
end
end
struct A
card::Card
function A()
new(Card("A", [1,11]))
end
end
struct C2
card::Card
function C2()
new(Card("C2", [2]))
end
end
In the REPL, we see that the structs don’t behave well with equality.
julia> c = C2()
C2(Card("C2", [2]))
julia> c2 = C2()
C2(Card("C2", [2]))
julia> c == c2
false
julia> c ≂ c2
true
julia> C2() in [C2(), C2()]
false
How could I tweak == in order to use in
, and ==
as expected?