Hello all!
I'm learning Nim and trying to solve exercise 3 from here:
Points in 2D plane can be represented as tuple[x, y: float]. Write a procedure which will receive two points and return a new point which is a sum of those two points (add x’s and y’s separately).
I solved it as following:
type Point2D = tuple[x, y: float]
proc sumPoints(p1: Point2D, p2: Point2D): Point2D =
result.x = p1.x + p2.x
result.y = p1.y + p2.y
echo sumPoints(Point2D (x: 1.0, y: 2.0), Point2D (x: 3.0, y: 4.0))
My code works, but I seems to me there is more simple way to solve this exercise.
Any ideas?
type Point2D = (float, float)
proc sumPoints(p1: Point2D, p2: Point2D): Point2D = (p1[0] + p2[0], p1[1] + p2[1])
echo sumPoints((1.0, 2.0), (3.0, 4.0))
is possible.
In Python this will be like so:
from dataclasses import dataclass # Python >= 3.7
@dataclass
class Point2D:
x: float
y: float
def sumPoints(p1: Point2D, p2: Point2D) -> Point2D:
x = p1.x + p2.x
y = p2.y + p2.y
return Point2D(x, y)
print(sumPoints(Point2D(1.0, 2.0), Point2D(3.0, 4.0)))
You can also use auto as the return type. https://nim-lang.github.io/Nim/manual.html#types-auto-type
type Point2d = tuple[x, y: float]
proc sumPoints(p1, p2: Point2D): auto = (p1.x + p2.x, p1.y + p2.y)
echo sumPoints((1.0, 2.0), (3.0, 4.0))
@araq, @geekrelief, thanks for
echo sumPoints((1.0, 2.0), (3.0, 4.0))
type Point2D = tuple[x, y: float]
func sumPoints(p1, p2: Point2D): Point2D = (p1.x + p2.x, p1.y + p2.y)
echo sumPoints((x:1.0, y:2.0), (x:3.0, y:4.0))
Don't be repeating the type in the args, nor failing to qualify the x, y parameters in the call.
Would be nice if Nim supported object destructors:
func sumPoints((x1, y1), (x2, y2): Point2D): Point2D = (x1 + x2, y1 + y2)