Recursion without arguments and static variables - recursion

I was asked to write a recursive function to print a singly linked list. But my instructor told me that you can not use static variables or arguments in the function. Is recursion really possible without arguments and static variables?
void recursivePrint() const;

Yes, it is possible. Since recursivePrint() is a member function, you merely have to print the value at the head, and then recursively print the rest of the list:
void recursivePrint() const {
if (!head) {
return;
}
std::cout << head->value << " ";
if (head->next) {
head->next->recursivePrint();
}
}

Related

Is `R_ClearExternalPtr()` needed to finalize an external pointer object in R?

While reading Writing R Extensions, Section 5.13 External pointers and weak references we see an example of a finalizer using R_ClearExternalPtr() albeit the comment next to it saying not really needed:
(...) The finalizer code is simply
static void chanFinalizer(SEXP ptr)
{
if(!R_ExternalPtrAddr(ptr)) return;
inRODBCClose(R_ExternalPtrAddr(ptr));
R_ClearExternalPtr(ptr); /* not really needed */
}
In the post Storing C objects in R by #Martin-Morgan he provides two finalizer examples, where he does include a call to R_ClearExternalPtr() in the first case but not in the second:
First example:
static void
_finalizer(SEXP ext)
{
if (NULL == R_ExternalPtrAddr(ext))
return;
Rprintf("finalizing\n");
char *ptr = (char *) R_ExternalPtrAddr(ext);
Free(ptr);
R_ClearExternalPtr(ext);
}
Second example:
static void
_finalizer(SEXP ext)
{
struct Foo *ptr = (struct Foo*) R_ExternalPtrAddr(ext);
Free(ptr);
}
Can someone help clarify the comment not really needed, and whether I should call R_ClearExternalPtr() at the end of the finalizer.

static vector in recursion vs global vector

USING GLOBAL VECTOR
vector<int> r;
vector<int> inorderTraversal(TreeNode* root) {
if(root==NULL)
return r;
inorderTraversal(root->left);
r.push_back(root->val);
inorderTraversal(root->right);
return r;
}
I am getting answer for all test cases but when using below code I am getting answer when running separately but when I finally submit test cases are failing(input of empty tree) like I am getting Output for some other input why is this happenning?
vector<int> inorderTraversal(TreeNode* root) {
static vector<int> r;
if(root==NULL)
return r;
inorderTraversal(root->left);
r.push_back(root->val);
inorderTraversal(root->right);
return r;
}
If you say the first version works, then I assume your "global" variable is actually an instance variable of a class. In that case that variable is a new variable every time the test suite creates a new instance of the class.
A static local variable however will retain its value even when the function is executed on a new instance of the class of which it is a method.
A solution is to not make it static, and then overload the method, so it can take that r as second parameter:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> r;
return inorderTraversal(root, r);
}
vector<int> inorderTraversal(TreeNode* root, vector<int> r) {
if(root==NULL)
return r;
inorderTraversal(root->left, r);
r.push_back(root->val);
inorderTraversal(root->right, r);
return r;
}

How to create a QFuture with an immediately available value?

I have a function which returns QFuture object as a result of a QtConcurrent::run computation. However, there could be some conditions before running the concurrent method where I need to manually return a value-holding future from my function.
QFuture<bool> foo(const QString &bar)
{
if (bar.isEmpty()) {
return QFuture<bool>(false); // This does not work.
// Here I need to return from the function, but I don't know how to do it.
}
return QtConcurrent::run([=]() -> bool {
// Asynchronous computations...
});
}
How to manually create the QFuture object?
Or (more globally) how to properly return from such method?
When there's no data to return, things are easy - this should be the first thing to try anyway in modern C++:
return {};
Or, if you're targeting some obsolete platform (<Qt 5.6):
return QFuture<bool>();
That way you get an invalid future. There's no way to directly create a future that carries preset data, you'd have to use QFutureInterface for that:
// https://github.com/KubaO/stackoverflown/tree/master/questions/qfuture-immediate-50772976
#include <QtConcurrent>
template <typename T> QFuture<T> finishedFuture(const T &val) {
QFutureInterface<T> fi;
fi.reportFinished(&val);
return QFuture<T>(&fi);
}
QFuture<bool> foo(bool val, bool valid) {
if (!valid)
return {};
return finishedFuture(val);
}
int main() {
Q_ASSERT(foo(true, true));
Q_ASSERT(!foo(false, true));
Q_ASSERT(foo(false, false).isCanceled());
Q_ASSERT(foo(true, false).isCanceled());
}

Pass a typed function as a parameter in Dart

I know the Function class can be passed as a parameter to another function, like this:
void doSomething(Function f) {
f(123);
}
But is there a way to constrain the arguments and the return type of the function parameter?
For instance, in this case f is being invoked directly on an integer, but what if it was a function accepting a different type?
I tried passing it as a Function<Integer>, but Function is not a parametric type.
Is there any other way to specify the signature of the function being passed as a parameter?
Dart v1.23 added a new syntax for writing function types which also works in-line.
void doSomething(Function(int) f) {
f(123);
}
It has the advantage over the function-parameter syntax that you can also use it for variables or anywhere else you want to write a type.
void doSomething(Function(int) f) {
Function(int) g = f;
g(123);
}
var x = <int Function(int)>[];
int Function(int) returnsAFunction() => (int x) => x + 1;
int Function(int) Function() functionValue = returnsAFunction;
To strongly type a function in dart do the following:
Write down the Function keyword
Function
Prefix it with its return type (for example void)
void Function
Append it with parentheses
void Function()
Put comma separated arguments inside the parentheses
void Function(int, int)
Optionally - give names to your arguments
void Function(int foo, int bar)
Real life example:
void doSomething(void Function(int arg) f) {
f(123);
}
Edit: Note that this answer contains outdated information. See Irn's answer for more up-to-date information.
Just to expand on Randal's answer, your code might look something like:
typedef void IntegerArgument(int x);
void doSomething(IntegerArgument f) {
f(123);
}
Function<int> seems like it would be a nice idea but the problem is that we might want to specify return type as well as the type of an arbitrary number of arguments.
For reference.
int execute(int func(int a, int b)) => func(4, 3);
print(execute((a, b) => a + b));
You can have a function typed parameter or use a typedef
void main() {
doSomething(xToString);
doSomething2(xToString);
}
String xToString(int s) => 's';
typedef String XToStringFn(int s);
void doSomething(String f(int s)) {
print('value: ${f(123)}');
}
void doSomething2(XToStringFn f) {
print('value: ${f(123)}');
}
DartPad example
This is what typedefs are for!

vector base derived class

I am not able to call negedge of all the subscribers who register for clock, all subscribers also derive from ClkIf
class ClkAdapter : public ClkIf
{
virtual void negedge()
{
for(std::list<ClkIf*>::iterator it = clk_list.begin(); it != clk_list.end(); it++)
(it->negedge)();
}
virtual void posedge()
{ clk_cnt++; }
void registerForClock(ClkIf* module)
{ clk_list.push_back(module); }
std::list<ClkIf*> clk_list;
unsigned long long clk_cnt;
};
error: request for member 'negedge' in '* it.std::_List_iterator<_Tp>::operator-> with _Tp = ClkIf*', which is of non-class type 'ClkIf*'
Error in negedge function, What is wrong in this code??
You have a list of pointers, so the list iterator would work similarly to a double pointer (that is, ClkIf**). Thus, you would have to call (*it)->negedge() within the loop. The (*it) fetchs the current ClkIf* element first, and then the -> operator calls the function on that value.

Resources