Vector Physics
vector_physics.nr89 lines
vector_physics.nr· neuro
// Operator traits driving a vector physics step. Integration example: `+`, `-`,
// unary `-`, `==` and `!=` on a `Copy` struct, an `impl` block with an `&self` method, `+=`
// through the `Add` impl where no `AddAssign` is written, `-=` through a `SubAssign` impl,
// `if` expressions, and a `while` loop. The operators dispatch to trait methods and are
// monomorphized to plain calls. `PartialEq` is written by hand rather than derived, to show
// that an impl giving only `eq` gets `!=` from the trait's provided `ne`.
@derive(Copy, Clone)
struct Vec2 {
x: i32,
y: i32
}
impl Add for Vec2 {
type Output = Vec2
func add(self, rhs: Vec2) -> Vec2 {
Vec2 { x: self.x + rhs.x, y: self.y + rhs.y }
}
}
impl Sub for Vec2 {
type Output = Vec2
func sub(self, rhs: Vec2) -> Vec2 {
Vec2 { x: self.x - rhs.x, y: self.y - rhs.y }
}
}
impl Neg for Vec2 {
type Output = Vec2
func neg(self) -> Vec2 {
Vec2 { x: -self.x, y: -self.y }
}
}
impl PartialEq for Vec2 {
func eq(&self, rhs: &Vec2) -> bool {
self.x == rhs.x && self.y == rhs.y
}
}
impl SubAssign for Vec2 {
func sub_assign(&mut self, rhs: Vec2) {
self.x -= rhs.x
self.y -= rhs.y
}
}
impl Vec2 {
// Manhattan distance from the origin: an `&self` query method.
func manhattan(&self) -> i32 {
val ax = if self.x < 0 { -self.x } else { self.x }
val ay = if self.y < 0 { -self.y } else { self.y }
ax + ay
}
}
func main() -> i32 {
mut pos = Vec2 { x: 0, y: 0 }
val vel = Vec2 { x: 2, y: 3 }
// Integrate four steps: `+=` dispatches through the `Add` impl.
mut steps = 0
while steps < 4 {
pos += vel
println("step {steps}: pos = ({pos.x}, {pos.y})")
steps += 1
}
// pos = (8, 12)
mut result = 0
val target = Vec2 { x: 8, y: 12 }
if pos == target {
result += pos.manhattan() // 8 + 12 = 20
}
val back = pos - vel // (6, 9)
val flipped = -back // (-6, -9)
println("pos == target -> manhattan = {result}")
println("pos - vel (Sub impl) = ({back.x}, {back.y})")
println("-back (Neg impl) = ({flipped.x}, {flipped.y})")
result += flipped.manhattan() // 20 + 15 = 35
// One step back in place: `-=` dispatches through the `SubAssign` impl.
pos -= vel
println("pos -= vel (SubAssign) = ({pos.x}, {pos.y}), back: {pos == back}, off target: {pos != target}")
println("total = {result}")
result
}
neuroc run vector_physics.nr
step 0: pos = (2, 3)
step 1: pos = (4, 6)
step 2: pos = (6, 9)
step 3: pos = (8, 12)
pos == target -> manhattan = 20
pos - vel (Sub impl) = (6, 9)
-back (Neg impl) = (-6, -9)
pos -= vel (SubAssign) = (6, 9), back: true, off target: true
total = 35