XOR operation/type

I’ve been fiddling around with ideas trying to find how would a xor type would look like.

I wonder if there’s been any conversation for a ^ operator between types.
So far, and just for fun I have this as a naive idea:

Types = Dry.Types()

One = Types::Coercible::Symbol.enum(*%i(a b c))
Two = Types::Coercible::Symbol.enum(*%i(c d e))

XOR = Types.Instance(Dry::Types::Type).append do |type|
  type >> -> (input) do
    raise TypeError unless type.left.valid?(input) ^ type.right.valid?(input)

    type[input]
  end
end

Options = XOR[One | Two]

Options[:a]
# => :a

Options[:c]
# Dry::Types::CoercionError: TypeError

This whole thing stems from the idea of having one one potential path through the types so if there’s any overlap it’d fail loudly.

1 Like