0

I am trying to build up a time series using an autoregressive formula in Scala. The equation looks to the prior index of the target array and the current index of two other arrays. Example dummy equation: z_i = z[i-1] - x[i] + y[i]

It is straightforward in an imperative style (see C++ example below) but I am trying to figure out the idiomatic way in Scala. I have created a solution with a while loop but it feels clunky and un-Scalaesque.

#include <vector>
#include <iostream>

int main() {
  std::vector<int> x {1, 2, 3, 4};
  std::vector<int> y {10, 9, 8, 7};
  std::vector<int> z {0, 0, 0, 0};

  for(int i = 1; i < x.size(); i++) {
      z[i] = z[i-1] - x[i] + y[i];
  }

  for(auto i: z) {
      std::cout << i << std::endl;
  }
}

// Desired result
[0, 7, 12, 15]

1 Answer 1

2

Instead of modifying an existing z, you'll want to build it from x and y.

val x = Vector(1, 2, 3, 4)
val y = Vector(10, 9, 8, 7)
val z = (x.tail zip y.tail).scanLeft(0){case (nz,(nx,ny)) => nz - nx + ny}
//z: Vector[Int] = Vector(0, 7, 12, 15)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.