Re: Binary operators for cubes - Mailing list pgsql-hackers

From Dean Rasheed
Subject Re: Binary operators for cubes
Date
Msg-id CAEZATCVOoYjj_iwVhzzHXDdMea9xFjdX05KK61JB-7f9UYZ49w@mail.gmail.com
Whole thread Raw
List pgsql-hackers
On Thu, 15 May 2025 at 16:16, Kirill Panin <kipanin@edu.hse.ru> wrote:
>
> Hi hackers!
>
> The "cube" extention is frequently used for vectors, but the current
> implementation lacks support for binary operators, such as +, -, *, /.
> The attached (fairly trivial) patch adds support for these with the
> required documentation and test changes.
>

I don't think that your definition of addition and subtraction makes
sense for type cube. The docs say:

    It does not matter which order the opposite corners of a cube are
    entered in. The cube functions automatically swap values if needed to
    create a uniform “lower left — upper right” internal representation.

Thus, for example, the following 2 cubes are equal:

SELECT '(0,0), (10,10)'::cube = '(10,0), (0,10)'::cube;

 ?column?
----------
 t
(1 row)

However, with your definition of addition in terms of simple pointwise
addition of coordinates, the results of adding this cube to another
are different, depending on the order of the corners:

SELECT '(0,0), (10,10)'::cube + '(1,2), (3,4)'::cube,
       '(10,0), (0,10)'::cube + '(1,2), (3,4)'::cube;

    ?column?     |    ?column?
-----------------+-----------------
 (1, 2),(13, 14) | (11, 2),(3, 14)
(1 row)

which are not equal. It's a pretty odd form of addition in which a+c
differs from b+c when a and b are the equal.

One could define point+point and point+cube addition to be translation
by the values from the point, and then it would work correctly if the
corners of the cube were reversed. That makes a certain amount of
geometrical sense, since then multiplication and addition are just
scale and translate.

I imagine that people using the cube extension for vectors are using
zero-volume cubes (points), so translation-addition would work the
same as normal vector addition in that case. However, I doubt that
cube is ever going to make a good general-purpose type for vectors. It
would be somewhat odd to allow dot and cross products of cubes, for
example.

Regards,
Dean



pgsql-hackers by date:

Previous
From: Anthonin Bonnefoy
Date:
Subject: Don't keep closed WAL segment in page cache after replay
Next
From: Peter Eisentraut
Date:
Subject: Re: Replace magic numbers with strategy numbers for B-tree indexes