```fun Vector.times(other: Vector) = zip(other, Do...
# codingconventions
h
Copy code
fun Vector.times(other: Vector) = zip(other, Double::times).toVector()
or
Copy code
fun Vector.times(other: Vector) = zip(other) { a, b -> a * b }.toVector()
?
1️⃣ 5
m
Am I the only one who thinks that this:
Copy code
fun Vector.times(other: Vector) = Vector(this.x * other.x, this.y * other.y)
Is not only faster but also more readable.
👍 1
h
Your solution does not support vectors of any length. Also, I think I was doing dot product, so it'd be
zip(other, Double::times).sum()
In general I don't like performing operations inside the arguments/parameters block unless they are very simple like in your example.
j
Zip isn't great for arbitrary length either, unless you really want to use just the intersection of the two. I would prefer the static one from above as that at least forces equal length and thus has clear semantics in that regard.
m
Ow, sorry. You mean Java Vector. If, so this multiplication behaves like that? We should base on math. If we treat it like a matrix it is a scalar multiplication (or vectorized operation https://au.mathworks.com/help/matlab/matlab_prog/vectorization.html). Matrix multiplication behaves differently. If you treat it as a math vector, it should also be a different operation (https://en.wikipedia.org/wiki/Multiplication_of_vectors).
h
I actually implemented my own Vector class. I was more using it as an established concept, but failed.
Vectors have two forms of multiplication: Outer product of vectors produces a matrix. Inner product produces a number.
to be exact, my implementation of Vector::times is the following:
Copy code
operator fun Vector.times(other: Vector): Double {
   if (size != other.size) error("Vector inner product requires vectors of equal length: $size != ${other.size}")
   
   return zip(other, Double::times).sum()
}
j
apart from performance and the runtime error there is nothing wrong with that. Bit off topic (because it's not possible in kotlin), that's where the type level hackery you can do in languages like haskell or even easier agda is just unmatched, you could easily get both no runtime errors and a fast implementation. Oh and back to the original question: 1️⃣ is definitly nicer to read.
h
Yeah, I can't use the syntax suggested by Markin because my Vector class is basically just a List and so it does not have specific
x, y, ...
fields