I am having problems translating C++ data structures to Scala. Scala is really different from C++, but I like a lot of it. I have the following Code fragment in C++:
struct Output
{
double point;
double solution[6];
};
struct Coeff
{
double rcont1[6];
double rcont2[6];
double rcont3[6];
double rcont4[6];
double rcont5[6];
double rcont6[6];
};
std::list<Output> output;
std::list<Coeff> coeff;
I now fill the list in a while loop with data
while(n<nmax) {
if step successfull
Output out;
out.point = some values;
out.solution[0] = some value;
output.push_back(out);
}
I tried creating a simple class in Scala to hold the data.
class Output
{
var point: Double
var solution: Array[Double] = new Array(6)
}
But this doens't work since point is not initialized. Is there a way around this? I just want to define the variable but not initialize it.
Another quick thing. I am looking for an equivalent to stl::lower_bound.
Is finds the right position to insert an element in an sorted container to maintain the order.
Thanks for helping a Scala beginner
Why don't you want to initialize it? For efficiency? I'm afraid that the JVM doesn't let you get away with having random junk in your variables based on whatever was there originally. So since you have to initialize it anyway, why not specify what your "uninitialized" value is?
class Output {
var point = 0.0
var solution = new Array[Double](6)
}
(You could use Double.NaN
and check for point.isNaN
if you later need to see whether the value has been initialized or not.)
You could use _
as the default initialization, but unless you use it in generic code:
class Holder[T] {
var held: T = _
}
then you're just obscuring what the value really will be set to. (Or you are announcing "I really don't care what goes here, it could be anything"--which could be useful.)
I just found the answer to the intialistion:
class Output
{
var point: Double = _
var solution: Array[Double] = Array(6)
}
Puh Scala has a lot of syntx to get used to :-)
Anyone have a solution for the lower_bound equivalent ?
It's hard to translate effectively, as you've left a lot of unknowns hidden behind pseudo code, but I'd advocate something along these lines:
// type alias
type Coeff = Seq[Seq[Double]]
// parameters passed to a case class become member fields
case class Output (point: Double, solution: Seq[Double])
val outputs = (0 to nmax) map { n =>
Output(generatePoint(n), generateSolution(n))
}
If you can flesh out your sample code a bit more fully, I'll be able to give a better translation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With