Different inputs for the same function - c++

So I have a function that takes in 2 different inputs.
I've ran into the situation, however, where I very occasionally need a third input. Most of the time I don't though.
The solution I currently have is that the actual function I want to use is only called by 2 other functions. These two functions have the same name, but 1 takes 3 input and the other 2 (with this one just setting a null value to the third input before calling the original function).
This works quite well, but it feels like there might be a much better way of handling this type of problem. The only other solution I have is to declare a null value of the third input every time I go to call the first function, but that seems even messier.
Is there a better way to do this? Is it bad form the way I've written it?

Default arguments:
void foo (int x, int y, int z = 0);
Unless you pass a third value, z will be 0 by default inside the function.

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?

Validate function parameters based on given constraints

Before saying anything, please let me make it clear that this question is NOT language-specific but part of my work on an interpreter.
Let's say we have an enum of Value types. So a value can be:
SV, // stringValue
IV, // integerValue
AV, // arrayValue
etc, etc
then let's say we have a function F which takes one of the following combinations of arguments:
[
[SV],
[SV,IV],
[AV]
]
Now, the function is called, we calculate the values passed, and get their types. Let's say we get [XV,YV].
The question is:
What is the most efficient way to check if the passed values are allowed?
(The original interpreter is written in Nim, so one could say we could lookup the value array in the array of accepted value arrays like: accepted.contains(passed) - but this is not efficient)
P.S. ^ That's how I'm currently doing it, although I've explored the option of using bitmasks too. However, I cannot seem how it would help, since order plays an important part too.

Clojure creating higher order first function

; Now create a function that takes a function (which produces a sequence)
; as an argument. Your function should invoke that function and return and
; return the first element from the returned sequence.
(is (higher-order-first-function? __))
Guys it is actually a part of my homework. I have 1000 lines of codes to do. This is just a part that i could not figure out how to do it. Can anyone help me how to solve this ? I tried every possible way but. I could not pass the testing.
So the steps are pretty clear from the comments:
Write a function that expects one parameter (use defn, fn, or #())
That parameter should be a function, so check for that (fn?)
Call that function
Return the first element in the returned sequence (first)

Elegant way to pass multiple arguments to a function

I've got a function which looks like this:
bool generate_script (bool net, bool tv, bool phone,
std::string clientsID,
std::string password,
int index, std::string number,
std::string Iport, std::string sernoID,
std::string VoiP_number, std::string VoiP_pass,
std::string target, int slot, int port,
int onu, int extra, std::string IP, std::string MAC);
In my opinion it looks ugly. What is the proper way of handling this problem? Should I create few vectors with different data types (int, string and bool) and pass them as arguments to this function?
If all these parameters are meaningfully related, pack them in a structure.
Put them in a struct
Create a structure
struct GenerateScriptParams { /* ... */ };
and put all the parameters in there. You can actually provide default values for the initialization of the struct as well by implementing a default constructor or, in C++11, by providing default initialization of individual members. You can then change the values that are not supposed to be defaulted. This selective picking of non-default parameters is not possible for a function call with lots of parameters in C++.
Making the interface nice for the caller
Yet, the usage is a little ugly, since you have to create a temporary name object, then change the values that should not be default and then pass the object to the function:
GenerateScriptParams gsp;
gsp.net = true;
gsp.phone = false;
gps.extra = 10;
generate_script( gsp );
If you call that function in several different places, it makes sense to avoid this uglyness by providing mutating member functions that can be chained:
GenerateScriptParams & GenerateScriptParams::setNet ( bool val );
GenerateScriptParams & GenerateScriptParams::setTV ( bool val );
GenerateScriptParams & GenerateScriptParams::setPhone( bool val );
// ... //
Then calling code can write
generate_script( GenerateScriptParams()
.setNet(true),
.setPhone(false),
.setExtra(10) );
without the above uglyness. This avoids the named object that is only used once.
I personally do not believe that moving all the arguments in one struct will make the code much better. You just move dirt under the carpet. When you are going to deal with the creation of the struct you have the same problem.
The question is how much reusable this struct will be? If you end up with a 18 parameters for one function call something it is not quite right in your design. After further analysis you may discover that those parameters can be group in several different classes and those classes could be aggregated to one single object that will be the input of your function. You may want also prefer classes to struct in order to protect your data.
EDIT
I will give you a small example to describe why several classes are better than one monolithic struct. Let's start counting the tests that you need to write to cover the function above. There are 18 parameters as input (3 boolean). So we are going to need at least 15 tests only to validate the input (assuming the values are not interconnected).
The overall number of tests is impossible to be calculated without the implementation, but we can have an idea of the magnitude. Let take the lower bound all the input can be treat as boolean the number of possible combination are 2^18 so around 262000 tests.
Now, what happen if we split the input in several objects?
First of all, the code to validate the input is moved away from the function to the body of every single object (and it can be reused).
But more importantly the number of tests will collapse, let say in group of four (4,4,4 and 4 params per object) the total number of tests is only:
2^4 + 2^4 + 2^4 + 2^4 + 2^4 = 80
The fifth attributes is due to the permutation of the objects with themselves.
So, what is more cost demanding? Write thousand of tests or few more classes?
Obviously, this is a crude simplification, however, it will underlying the core of the problem. A clutter interface is not just matter of style or an inconvenient for the developer it is a true impediment to produce quality code.
This is the most important lesson I ever learnt in my career as a professional developer: "Big classes and fat interfaces are evil". That's just my heuristic version of the single responsibility principle (I have notice that the SRP can be tricky to get it right, what it seems reasonable to be single responsibility it can be not quite the same after a hour coding, so I used some heuristic rule to help me to revaulate my initial choices).
Or you could use a fluent interface. It would look like this:
script my_script(mandatory, parameters);
my_script.net(true).tv(false).phone(true);
This is applicable if you have default values for your specified parameters or it is allowed to have a partially constructed script.
Ignoring the possibility or desirability of changing the function or program in some way as to reduce the number of parameters...
I have seen coding standards that specify how long parameter lists should be formatted, for cases where refactoring is not possible. One such example is using double indentations and one parameter per line (Not for all functions - only for those that have multiple-lines of parameters).
E.g.
bool generate_script (
bool net,
bool tv,
bool phone,
std::string clientsID,
std::string password,
int index,
std::string number,
std::string Iport,
std::string sernoID,
std::string VoiP_number,
std::string VoiP_pass,
std::string target,
int slot,
int port,
int onu,
int extra,
std::string IP,
std::string MAC);
The point here is to create a consistent layout and look for all functions with a large number of parameters.
A bit late here, but since nobody has done it yet, I'd like to point out an obvious aspect of the issue: to me, a function which takes so many arguments is likely to do a lot of computation, so consider the possibility of decomposing it in smaller functions as a first step.
This should help you structuring your data.

What's the real purpose of `ignore` function in OCaml?

There is an ignore function in OCaml.
val ignore : 'a -> unit
Discard the value of its argument and return (). For instance,
ignore(f x) discards the result of the side-effecting function f. It
is equivalent to f x; (), except that the latter may generate a
compiler warning; writing ignore(f x) instead avoids the warning.
I know what this function will do, but don't get the point of using it.
Anyone can explain or give an example for when we have to use it?
You basically answered your own question. You don't ever have to use it. The point is precisely to avoid the warning. If you write f x; (), the compiler assumes you probably did something wrong. Probably you thought f x returns unit because you rarely want to ignore non-unit values.
However, sometimes that's not true, and you really want to ignore even non-unit values. Writing ignore (f x) documents the fact that you know f x returns something, but you are deliberately ignoring it.
Note that in real code f x might be something more complex, so the chances of you being wrong about the return type of f x are reasonably high. One example is partial application. Consider f : int -> int -> unit. You might accidentally write f 1, forgetting the second argument, and the warning will help you. Another example is if you do open Async, then many functions from the Standard Library change from returning unit to returning unit Deferred.t. Especially when first starting to use Async, it is quite likely that you'll accidentally think the semicolon operator is appropriate in places that you really need to use monadic bind.
As a complement to Ashish Agarwal's answer (because judging from your comment you don't seem very convinced) :
Imagine that I have a function that has side effects, and returns a value indicating something about the computation. Then, if I'm interested in how the computation went, I will need its return value. However, if I don't care about this and simply want the side effects to take place, I would use ignore.
Dumb example : let's say you have a function which sorts an array and returns Was_already_sorted or Was_not_sorted depending on the initial state of the array. Then if for some reason I'm interested in knowing how often my array was sorted, I might need the return value of this function. If not, I will ignore it.
I agree that this is a dumb example. And probably that in many cases there would be better ways to deal with the problem than using ignore (I've just noticed that I never use ignore). If you're really passionate about this, you could try to find examples of use of this function in real-life code (maybe in the source-code of software such as Unison?).
Also, note that you can use let _ = f x to the same end.