This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
record Vector(double X, double Y, double Z)
{
public static Vector operator *(Vector a, Vector b)
{
return new(
a.Y*b.Z - a.Z*b.Y,
a.Z*b.X - a.X*b.Z,
a.X*b.Y - a.Y*b.X
);
}
}
C# allows operator overloading but not operators with user-defined names.
Because it is ambiguous whether the * operator between two vectors is dot product, cross product, or component-wise multiplication, each of these should be implemented as a static method instead.
Refer to the built-in 3D vector type, linked as 'Origin'
Because it is ambiguous whether the * operator between two vectors is dot product, cross product, or component-wise multiplication, each of these should be implemented as a static method instead.
Refer to the built-in 3D vector type, linked as 'Origin'
module vect
private
type, public:: vector
real :: x,y,z
end type vector
public:: operator(.x.)
interface operator(.x.)
procedure vector_cross
end interface operator(.x.)
contains
function vector_cross(a,b) result(c)
type(vector), intent(in) :: a,b
type(vector) :: c
c%x = a%y*b%z - a%z*b%y
c%y = a%z*b%x - a%x*b%z
c%z = a%x*b%y - a%y*b%x
end function vector_cross
end module vect
You can then write a .x. b in an expression.
class Vector {
has $x :accessor;
has $y :accessor;
has $z :accessor;
BUILD { ($x, $y, $z) = @_ }
use overload 'x' => sub { shift->xprod(shift) };
method xprod ($v) {
return Vector->new(
$self->y * $v->z - $self->z * $v->y,
$self->z * $v->x - $self->x * $v->z,
$self->x * $v->y - $self->y * $v->x,
);
}
}
my $a = Vector->new(3, 4, 5);
my $b = Vector->new(5, 10, 1);
my $cross = $a x $b;
This is the modern perl way to do it, using an OO module such as Object::Pad.
package Vector {
sub new {
my ($class, $x, $y, $z) = @_;
bless [$x,$y,$z], $class;
}
sub x { shift->[0] };
sub y { shift->[1] };
sub z { shift->[2] };
use overload 'x' => sub { shift->xprod(shift) };
sub xprod {
my ($self,$v) = @_;
return Vector->new(
$self->y * $v->z - $self->z * $v->y,
$self->z * $v->x - $self->x * $v->z,
$self->x * $v->y - $self->y * $v->x,
);
}
}
Perl classic OO (i.e. not using module like Moose or Object::Pad) which defines a Vector class. See demo for more. Arguments are passed as a list; Operator shift removes the first item from the list, usually $self (or $class).
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
return
def __mul__(self, other):
return Vector(self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x)
result = a * b
Python doesn't allow operators with user-defined names
class Vector:
def __init__(self, x, y, z):
self.a = x, y, z
def __getitem__(self, i):
return self.a[i]
def __mul__(self, b):
a = self.a
return {
'x': a[1] * b[2] - a[2] * b[1],
'y': a[2] * b[0] - a[0] * b[2],
'z': a[0] * b[1] - a[1] * b[0]
}
a = Vector(.1, .2, .3)
b = Vector(.4, .5, .6)
x = a * b