Ok so I thought this would be a snap, trying to practice Scala’s collection operators and my example is a list of points.
The class can calculate and return the distance to another point (as double).
However, fold left doesn’t seem to be the right solution – considering elements e1, e2, e3.. I need a moving window to calculate, I need the last element looked at to carry forward in the function – not just the sum
Sum {
e1.dist(e2)
e2.dist(e3)
etc
}
Reading the API I noticed a function called “sliding”, perhaps that’s the correct solution in conjunction with another operator. I know how to do this with loops of course, but trying to learn the scala way.
Thanks
import scala.math._
case class Point(x:Int, y:Int) {
def dist(p:Point) = sqrt( (p.x-x)^2+(p.y-y)^2 )
}
object Point {
//Unsure how to define this?
def dist(l:Seq[Point]) =l.foldLeft(0.0)((sum:Double,p:Point)=>)
}
If you want to do it as a fold, you can, but you need the accumulator to keep both the total and the previous element:
You finish with a tuple consiting of the last element and sum, so use
._2to get the sum part.btw,
^on Int is bitwise logical XOR, not power. Usemath.pow.The smartest way is probably using
zipped, which is a kind of iterator so you don’t traverse the list more than once as you would usingzip: