Class function returning invalid lvalue - c++

Hi I am now writing a program handling matrix manipulation and I am struggling on the error handling issue in a member function.
Given a function
double & MATRIX::elements(int i, int j) const;
it is the function that can return a reference back, so the function can be a
lvalue, e.g.
object.elements(1,2)= 2; // I can change the value matrix element (1,2) to be 2
I assume that some people may enter the index of the matrix wrongly (i.e.invalid value of i and j) that the element (i,j) does not exist. Therefore, I write an if-else statement, however, I wonder what should I return when invalid values of i and j are found?? Can I prevent the function from returning anything so situations like
object.elements(100,100000)= 2; // where the matrix size is only 3x3
won' t happen??
P.S. I store the matrix elements in a dynamic array when I create the object

There are three practical possibilities:
assert the precondition, and rely on testing to root out all invalid calls, or
throw an exception when the precondition is not true, or
return an easily recognized-as-such error value.
In the old days one also included schemes such as calling a user-provided error function, but really what could it do except terminate or throw an exception.
The third possibility, returning a known-as-such error value, may appear unsuitable for your present predicament, which ideally would return a double& which would be immediately used. But in general it's a valid option. For example, it can be implemented as a Boost optional.
In passing, some general advice.
For the given code,
double & MATRIX::elements(int i, int j) const;
usually a const method does not provide read/write access, it defeats the purpose. However there are exceptions, such as for a proxy object. But on the third and gripping hand, the above code is not for such objects.
Also, consider reserving ALL UPPERCASE identifiers for macros. That way you can avoid some name collisions. Remember that macros don't respect scopes, and since a great many people use all uppercase identifiers for macros, while few do otherwise, the chance of a collision, resulting in undesirable text substitution, is greater with uppercase used for ordinary identifiers.

Related

How to construct an XlaOp?

There are a number of functions for creating XlaOps from native C++ values. I'm trying to figure out how to use each to construct a graph. I've gone through xla_builder.h and picked out some candidates, omitting overloads and convenience wrappers. The two most likely candidates seem to be
// Enqueues a "retrieve parameter value" instruction for a parameter that was
// passed to the computation.
XlaOp Parameter(XlaBuilder* builder, int64 parameter_number, const Shape& shape,
const string& name);
// Enqueues a constant with the value of the given literal onto the
// computation.
XlaOp ConstantLiteral(XlaBuilder* builder, const LiteralSlice& literal);
Am I right in thinking Parameter is for "symbols", while ConstantLiteral is for constant values? For example, in f(x) = x + 1, we'd encode 1 as a ConstantLiteral, and then for x we could either
write f(x) as a C++ function, and at application site use another ConstantLiteral for our value of x, or
encode x using Parameter and build an XlaComputation from the corresponding XlaBuilder. That said, I'm not clear on how to actually call the XlaComputation with a Literal, other than with LocalClient which doesn't work with to multiple XlaComputations afaict.
What's the difference between these two approaches? Is one better than the other? I notice the former doesn't appear possible for higher-order functions: those which accept XlaComputations.
Next there's
Infeed, which I'd guess is a streaming version of Parameter.
Recv which looks like a way to pass data between computations, but doesn't actually create a completely new XlaOp itself.
ReplicaId, Iota, and XlaOp CreateToken(XlaBuilder* builder); appear largely irrelevant for this discussion.
Have I got this right? Are there any other important functions I've missed?

How to solve Syntax Error in Data Statement?

Hi I am new here and want to solve this problem:
do k=1,31
Data H(1,k)/0/
End do
do l=1,21
Data H(l,1)/0.5*(l-1)/
End do
do m=31,41
Data H(17,m)/0/
End do
do n=17,21
Data H(n,41)/0.5*(n-17)/
End do
I get error for l and n saying that it is a syntax error in DATA statement. Anyone know how to solve this problem?
You have three problems here, and not just with the "l" and "n" loops.
The first problem is that the values in a data statement cannot be arbitrary expressions. In particular, they must be constants; 0.5*(l-1) is not a constant.
The second problem is that the bounds in the object lists must also be constant (expressions); l is not a constant expression.
For the first, it's also worth noting that * in a data value list has a special meaning, and it isn't the multiplication operator. * gives a repeat count, and a repeat count of 0.5 is not valid.
You can fix the second point quite simply, by using such constructions as
data H(1,1:31) /31*0./ ! Note the repeat count specifier
outside a loop, or using an implied loop
data (H(1,k),k=1,31) /31*0./
To do something for the "l" loop is more tedious
data H(1:21,1) /0., 0.5, 1., 1.5, ... /
and we have to be very careful about the number of values specified. This cannot be dynamic.
The third problem is that you cannot specify explicit initialization for an element more than once. Look at your first two loops: if this worked you'd be initializing H(1,1) twice. Even though the same value is given, this is still invalid.
Well, actually you have four problems. The fourth is related to the point about dynamic number of values. You probably don't want to be doing explicit initialization. Whilst it's possible to do what it looks like you want to do, just use assignment where these restrictions don't apply.
do l=1,21
H(l,1) = 0.5*(l-1)
End do
Yes, there are times when complicated explicit initialization is a desirable thing, but in this case, in what I assume is new code, keeping things simple is good. An "initialization" portion of your code which does the assignments is far more "modern".

obfuscated C++ Translation: float&, two for loops

I was reading Hacker News and this article came up. It contains a raytracer that the code is written on the back of a business card. I decided it would be a good academic challenge to translate the c++ to python, but there's a few concepts I'm stuck on.
First, this function comes up: i T(v o,v d,f& t,v& n){...} Which is translated to int Tracer(vector o, vector d, float& t, vector& n){...} What does the float& mean? I know that in other places & is used as a == is that the case here? Can you do that in c++?
Second, I noticed these three lines:
for(i k=19;k--;) //For each columns of objects
for(i j=9;j--;) //For each line on that columns
if(G[j]&1<<k){
I know the << is a the bit shift, and I assume the & is ==. Are the for loops just like one for loop in an other?
Finally, this line: v p(13,13,13); I am not quite sure what it does. Does it create a class labeled by p that extends v (vector) with the defaults of 13,13,13?
These are probably dumb questions, but I want to see if I can understand this and my searching didn't come up with anything. Thank you in advance!
What does the float& mean?
Here, & means "reference", so the argument is passed by reference.
I know that in other places & is used as a == is that the case here?
& means various things in various contexts, but it never means ==. In this case, it's not an operator either; it's part of a type specification, meaning that it's a reference type.
I know the << is a the bit shift, and I assume the & is ==
No, it's a bitwise and operator. The result has its bits set where a bit is set in both operands. Here, with 1<<k as one operand, the result is the kth bit of G[j]; so this tests whether that bit is set.
Are the for loops just like one for loop in an other?
Yes. If you don't use braces around a for-loop's body, then the body is a single statement. So in this case, the body of the first loop is the second loop. To make this clear, I would recommend indenting the body of the loop, and using braces whether or not they are strictly necessary. But of course, I don't write (deliberately) obfuscated code.
Finally, this line: v p(13,13,13);
v is a class with a constructor taking three arguments. This declares an variable called p, of type v, initialised using that constructor; i.e. the three co-ordinates are initialised to 13.
When you seeVector& n it is referencing the vector passed into the function. This means that you can change n inside of this function without having to copy it to another Vector or without returning the Vector. This previous answer should be helpful to you.

SML programming help tuples

exception No_intersection of string
fun check_in ((m1:real, b1:real), (m2:real, b2:real)):real*real =
The function is supposed to check for an intersection between the two lines. Each pair argument is a slope and a y intercept. I am supposed to find the intersection between the two if it is exists.
I can't make to seem this work for some reason, and have been struggling with this for hours.
Reals are not an equality type in SML, so (m1-m2) = 0 is a type error.
The reason for this is that the limited precision of floating-point representations can give unexpected results due to rounding errors (e.g. (1.0/7.7)*7.7 = 1.0 would return false). You can get around this by using the == operator from the Real library, i.e. Real.==(m1-m2,0) (or just Real.==(m1,m2)). But keep in mind that it can be unreliable.
The second problem is that, according to the return type, your function is supposed to return a value, not print it. All you need to do here is state the return value in the else clause, i.e. just replace print((x,y)) with (x,y).
And for what it's worth, I'd avoid using exceptions if you can; they kind of go against the idea of functional programming. Try returning a (real*real) option instead.

Should I unit-test with data that should not be passed in a function (invalid input)?

I am trying to use TDD for my coding practice. I would like to ask should I test with a data that should not happen in a function BUT this data may possibly break your program.
Here is one of a easy example to illustrate to what I ask :
a ROBOT function that has a one INT parameter. In this function I know that the valid range would only be 0-100. If -1, 101 is used, the function will be break.
function ROBOT (int num){
...
...
...
return result;
}
So I decided some automated test cases for this function...
1. function ROBOT with input argument 0
2. function ROBOT with input argument 1
3. function ROBOT with input argument 10
4. function ROBOT with input argument 100
But should I write test cases with input argument -1 or 101 for this ROBOT function IF I would guard that in my other function that call function ROBOT???
5. function ROBOT with input argument -1
6. function ROBOT with input argument 101
I don't know if it is necessary cause I think it is redundancy to test -1 and 101. And If it is really necessary to cover all the cases, I have to write more code to guard -1 and 101.
So in Common practice of TDD, will you write test case on -1 and 101 as well???
Yes, you should test those invalid inputs. BUT, if your language has accessibility modifiers and ROBOT() is private you shouldn't be testing it; you should only test public functions/methods.
The functional testing technique is called Boundary Value Analysis.
If your range is 0-100, your boundary values are 0 and 100. You should test, at least:
below the boundary value
the boundary value
above the boundary value
In this case:
-1,0,1,
99,100,101
You assume everything below -1 to -infinity behaves the same, everything between 1-99 behaves the same and everything above 101 behaves the same. This is called Equivalence Partitioning. The ranges outside and between the boundary values are called partitions and you assume that they will have equivalent behaviour.
You should always consider using -1 as a test case to make sure nothing funny happens with negative numbers and a text string if the parameter is not strongly typed.
If the expected outcome is that an exception is thrown with invalid input values, then a test that the exceptions get properly thrown would be appropriate.
Edit:
As I noted in my comment below, if these cases will break your application, you should throw an exception. If it really is logically impossible for these cases to occur, then I would say no, you don't need to throw an exception, and you don't need test cases to cover it.
Note that if your system is well componentized, and this function is one component, the fact that it is logically impossible now doesn't mean it will always be logically impossible. It may be used differently down the road.
In short, if it can break, then you should test it. Also validate data at the earliest point possible.
The answer depends on whether you control the inputs passed to Robot. If Robot is an internal class (C#) ; values only flow in from RobotClientX which is a public type. Then I'd put the guard checks in RobotClientX, write tests for it. I'd not write tests for Robot, because invalid values cannot materialize in-between.
e.g. if I put my validations in the GUI such that all invalid values are filtered off at the source, then I don't check for invalid values in all classes below the GUI (Unless I've also exposed a public API which bypasses the GUI).
On the other hand, if Robot is publicly visible i.e. Anyone can call Robot with any value that they please, then I need tests that document it's behavior given specific kinds of input.. invalid being one of them. e.g. if you pass an out-of-range value, it'd throw an ArgumentException.
You said your method will raise an exception if the argument is not valid.
So, yes you should, because you should test that the exception gets raised.
If other code guards against calling that method incorrectly, and no one else will be writing code to call that method, then I don't see a reason to test with invalid values. To me, it would seem a waste of time.
The programming by contract style of design and implementation draws attention to the fact that a single function (method) should be responsible for only some things, not for everything. The other functions that it calls (delegates to) and which call it also have responsibilities. This partition of responsibilities is at the heart of dividing the task of programming into smaller tasks that can be performed separately. The contract part of programming by contract is that the specification of a function says what a function must do if and only if the caller of the function fulfills the responsibilities placed on the caller by that specification. The requirement that the input integer is within the range [0,100] is that kind of requirement.
Now, unit tests should not test implementation details. They should test that the function conforms to its specification. This enables the implementation to change without the tests breaking. It makes refactoring possible.
Combining those two ideas, how can we write a test for a function that is given some particular invalid input? We should check that the function behaves according to the specification. But the specification does not say what the function must do in this case. So we can not write any checks of the program state after the invalid function call; the behaviour is undefined. So we can not write such a test at all.
My answer is that, no, you don't want exceptions, you don't want to have to have ROBOT() check for out of range input. The clients should be so well behaved that they don't pass garbage values in.
You might want to document this - Just say that clients must be careful about the values they pass in.
Besides where are you going to get invalid values from? Well, user input or by converting strings to numbers. But in those cases it should be the conversion routines that perform the checks and give feedback about whether the values are valid or not. The values should be guaranteed to be valid long before they get anywhere near ROBOT()!