Call C++ recursive lambda in the same line where it is declared - c++

This is mostly a one liner style type of question, I would normally write this code in multiple lines anyway for readability reasons.
So my question is can I call the recursive lambda in the same statement where it is defined?
So instead of this:
int n=3;
function<void(int)> f {[n,&f](int i){if (i>1) { cout << "func(a, "; f(i-1); cout << ")";} else cout << "a";}};
f(n);
call the function with n in the same line where f is defined.

In one statement which declares several variables ;-)
Mostly not what you want:
std::function<void(int)>
f {[&f](int i){
if (i>1) {
std::cout << "func(a, "; f(i-1); std::cout << ")";}
else
std::cout << "a";
}},
dummy((f(3), nullptr));
Demo

Let me offer a glimpse into the functional programming world, where people usually use combinators to deal with recursive lambdas. There was a proposal (P0200r0) last year to add a simple Y-combinator to the standard library.
Leaving aside the question whether it is a good idea to do this, this would allow you to write and invoke a recursive lambda like this:
y_combinator([](auto self, int i){
if (i>1) {
std::cout << "func(a, ";
self(i-1);
std::cout << ")";
} else {
std::cout << "a";
}
})(6);
The basic idea here is that the y-combinator is a higher order function that wraps a lambda which is passed 'itself' as a first argument. The combinator takes care of wrapping the self argument away for all invocations of the lambda.
You can try it in coliru.

As a matter of fact, you can. Here is a complete example which compiles and runs fine with g++ -std=c++11:
#include <iostream>
#include <functional>
int main() {
std::function<int(int)> f = ([&f](int i){ return i?f(i-1)*i:1; }), trash = (std::cout << f(3) << std::endl, f);
}
However, I don't think it's a good idea to actually use this: The construct , trash = (..., f) would be in order for code golf or obfuscated programming contests, but would not meet my standards for production code.

What you are essentially asking for is to create a temporary instance of std::function and then invoke operator() on that object in the same statement. Both of these fail to compile for me with the same error when I try that:
function<void(int)> f{[&f](int i){ if (i > 1) { cout << "func(a, "; f(i-1); cout << ")"; } else cout << "a"; }}(n);
function<void(int)> f([&f](int i){ if (i > 1) { cout << "func(a, "; f(i-1); cout << ")"; } else cout << "a"; })(n);
error: expected ‘,’ or ‘;’ before ‘(’ token
Pointing at the ( of (n).
See #Jarod42's answer for a viable workaround, if you don't mind the extra variable initialization.
Alternatively, this would work, though it does have to use separate variable declaration and assignment:
function<void(int)> f; f = [&f](int i){ if (i > 1) { cout << "func(a, "; f(i-1); cout << ")"; } else cout << "a"; }, f(n);
Demo

Not sure if you consider it valid since it doesn't use lambda functions, but it is still single line and leaves no temporal variables behind ;)
struct {
struct R {
R(int i) {
if (i>1) { cout << "func(a, "; R(i-1); cout << ")"; }
else cout << "a";
}
} r;
} f{n};

Related

What am I iterating in this find_if function?

Here is my code:
bool isNotValid (char a) {
if (isalpha(a) || a == '_')
{
cout << "\n- isalpha";
return 0;
}
else
{
cout << "\n- notalpha";
return 1;
}
}
bool test123(const string& test)
{
return find_if(test.begin(), test.end(), isNotValid) != test.end();
}
int main()
{
string test;
cout << "Test input: ";
cin >> test;
if (!test123(test))
cout << "\n- Valid\n";
else
cout << "\n- Not Valid\n";
return 0;
}
This is part of my code to check the validity of username in my program. I don't really understand what exactly I am iterating through when I insert the string into my function as address of the string. CPP reference states that find_if iterates from first to last position of a sequence.
Poked through the code with cout at different location, still didn't quite catch what is going on.
You are iterating your string. You did not pass the address of the string. The function takes the string as a reference to const, meaning it passes the actual string (no copy is made) and the function is not allowed to modify the string. You are iterating character by character in your string and calling your function isNotValid() on each character.
Notes:
Instead of returning 1 or 0 from isNotValid(), return true or false.
Consider flipping your logic and renaming the function to isValid() instead. You would also have to change test123() to use std::find_if_not(). Finally, you would check if the returned iterator is end() and not if it's not.
But, if you do change isNotValid() to isValid(), you'd be better off switching from std::find_if() entirely to to std::all_of(). It makes more sense, is more readable, and returns a bool directly (No need to compare against end()).
But if you want to keep your function isNotValid(), the comment that suggests using std::any_of() is what I would recommend for the same reasons.
Here's my take on your code:
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
bool isValid(char a) {
return std::isalpha(static_cast<unsigned char>(a)) || a == '_'; // !
}
bool test123(const std::string& test) {
return std::all_of(test.begin(), test.end(), isValid); // !
}
int main() {
std::string testOne{"i_am_valid"};
std::string testTwo{"i_am_invalid_123"};
std::cout << "Testing: " << testOne << " : " << std::boolalpha
<< test123(testOne) << '\n';
std::cout << "Testing: " << testTwo << " : " << std::boolalpha
<< test123(testTwo) << '\n';
}
Output:
❯ ./a.out
Testing: i_am_valid : true
Testing: i_am_invalid_123 : false
I would argue that readability has stayed largely the same, but the mental load has been shifted; the Boolean flips make a bit more sense.
As you progress in your learning, you might not even want to have the function isValid() if it's a one-off thing. C++11 introduced lambdas, or functions as objects. C++20 also introduced ranges, so you don't have to pass a pair of iterators if you intend to iterate the whole container anyway.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
bool test123(const std::string& test) {
return std::ranges::all_of(test, [](const auto& c) {
return std::isalpha(static_cast<unsigned char>(c)) || c == '_';
}); // !
}
int main() {
std::string testOne{"i_am_valid"};
std::string testTwo{"i_am_invalid_123"};
std::cout << "Testing: " << testOne << " : " << std::boolalpha
<< test123(testOne) << '\n';
std::cout << "Testing: " << testTwo << " : " << std::boolalpha
<< test123(testTwo) << '\n';
}
That's a bit hairy to read if you're not familiar with lambdas, but I find lambdas useful for checks like this where you're just doing it the one time.

C++ Recursive Function Infinite Loop

I have a function which takes an int value from another function. When I type a wrong int value it works as intended (calls the same function recursively & lets me enter a new number) but when I type anything other than an int (a, %, etc) it calls the function recursively but gets stuck in an infinite loop. Any help/insight would be great as I am in the learning stages of C++ Programming.
Here is my Full code snippet (49 Lines)
To summarize what I am asking is how would I properly go about displaying an error and returning back to the Main Menu without triggering the infinite loop when a non-int value is given.
int MainMenu();
void MainMenuSelection(int x);
int main()
{
MainMenuSelection(MainMenu());
return 0;
}
int MainMenu() {
int selection;
std::cout << "C++ Tutorials Main Menu\n";
std::cout << "----------------------------------------------\n";
std::cout << "1 - Chapter #1\n";
std::cout << "2 - Chapter #2\n";
std::cout << "3 - Chapter #3\n";
std::cout << "----------------------------------------------\n";
std::cout << "Please enter a cooresponding value: ";
std::cin >> selection;
if (std::cin.fail()) {
std::cout << "Input must be an integer";
}
else {
return selection;
}
}
void MainMenuSelection(int x) {
if (x == 1) {
std::cout << "\nChapter #1 is unavailable.\n";
std::cout << std::string(22, '\n');
MainMenuSelection(MainMenu());
}
else if (x == 2) {
std::cout << std::string(2, '\n');
ChTwoMenuSelection(ChTwoMenu());
}
else if (x == 3) {
std::cout << std::string(2, '\n');
ChThreeMenuSelection(ChThreeMenu());
}
else {
std::cout << "\nThere was an incorrect value submitted.";
std::cout << std::string(22, '\n');
MainMenuSelection(MainMenu());
}
}
The function MainMenuSelection( int x ) requires an int. The function call in the main function thinks it gets this by calling a function which should return an int namely int MainMenu(). But this function does not do what you should expect from a function which has been declared in this way. You should make sure that a function should ALWAYS return the value (except for a void of course).
There are static code analyzers like Cppcheck which can help you to analyse your code and find possible problems like the one you stated above.
Another tip would be to think about what happens when you execute the code. Especially when your code is still quite small you can manually go through the statements to see what path it takes, so you can find out where the program fails.

calling function depending on index of array array of functions' names

making random actions in a game makes it really look like real...
so if a character has many capabilities like move, work, study... so in programming a function of those is called depending on some conditions. what we want is a more random and real-looking like action where no condition is there but depending on a random condition the character takes a random actions..
I thought to make actions (functions) in an array then declare a pointer to function and the program can randomly generate an index which on which the pointer to function will be assigned the corresponding function name from the array:
#include <iostream>
void Foo() { std::cout << "Foo" << std::endl; }
void Bar() { std::cout << "Bar" << std::endl; }
void FooBar(){ std::cout << "FooBar" << std::endl; }
void Baz() { std::cout << "Baz" << std::endl; }
void FooBaz(){ std::cout << "FooBaz" << std::endl; }
int main()
{
void (*pFunc)();
void* pvArray[5] = {(void*)Foo, (void*)Bar, (void*)FooBar, (void*)Baz, (void*)FooBaz};
int choice;
std::cout << "Which function: ";
std::cin >> choice;
std::cout << std::endl;
// or random index: choice = rand() % 5;
pFunc = (void(*)())pvArray[choice];
(*pFunc)();
// or iteratley call them all:
std::cout << "calling functions iteraely:" << std::endl;
for(int i(0); i < 5; i++)
{
pFunc = (void(*)())pvArray[i];
(*pFunc)();
}
std::cout << std::endl;
return 0;
}
the program works fine but I only is it good or there's an alternative. every comment is welcome
There is absolutely no point in converting function pointers to void* and back. Define an array of function pointers, and use it as a normal array. The syntax for the declaration is described in this Q&A (it is for C, but the syntax remains the same in C++). The syntax for the call is a straightforward () application after the indexer [].
void (*pFunc[])() = {Foo, Bar, FooBar, Baz, FooBaz};
...
pFunc[choice]();
Demo.
Note: Although function pointers work in C++, a more flexible approach is to use std::function objects instead.

How do I stream into a string without creating a named stringstream?

I often end up writing code like this:
SomeStreamableType x;
std::stringstream ss;
ss << "Value is: " << x;
log(ss.str());
The extra line needed to generate the stringstream feels superfulous. I can do this, but it's equally cumbersom:
SomeStreamableType x;
const std::string str = "Value is: " + boost::lexical_cast<std::string>(x);
log(str);
I want to be able to do this:
SomeStreamableType x;
log(std::stringstream() << "Value is: " << x);
Have others encountered this issue and come up with a workaround? I don't want to create any helper functions or classes.
Your code will work without modifications, as long as log accepts an ostream& reference:
void log(ostream& o) {
stringstream* s = dynamic_cast<stringstream*>(&o);
if (s) {
cout << s->str() << endl;
}
}
int main() {
int x = 5, y = 6;
log(stringstream() << "x=" << x << ", y=" << y);
return 0;
}
Demo.
To solve this problem I have often simply done something like this:
#define LOG(m) do{std::ostringstream oss;oss<<m;std::cout<<oss.str()<<'\n';}while(0)
// ...
LOG("some text: " << value1 << ' ' << value2); // no need for '\n'
Now I tend to use a more sophisticated class based solution that has an even nicer interface and doesn't use a horrible macro.

Code readability with c++11 lambdas

I REALLY love lambdas and having the ability to use them in C++ is a pleasure. But, as I'm used to Haskell, where lambdas fit really well into the syntax, I'm struggling with how to use them in C++ without writing unreadable cluttered long code lines.
So, as an example, suppose I'd write this:
vector<double> foo(10,0.2);
for_each(foo.begin(), foo.end(), [](double x){ std::cout << x << " ";})
this is not so difficult to read, the lambda expression is pretty small. But if I have a two or three line long function inside that for_each, this could become a problem for my
code-reading-skills:
vector<double> foo(10,0.2);
randomNumberGenerator bar;
for_each(foo.begin(), foo.end(), [](double x){ std::cout << "hello!"; x+=bar()/(1+bar()); std::cout << x << " ";})
//sorry, I couldn't think of a less stupid example...
This line is starting to get annoyingly long and difficult to read for my taste...
What is your preferred code conventions for this case? Should I write:
for_each(foo.begin(), foo.end(),
[] (double x) {
std::cout << "hello!"
x += bar()/(1+bar());
std::cout << x << " ";
});
or something like it? I still think this syntax feels a bit unnatural and difficult to read... :(
I usually go for
for_each(foo.begin(), foo.end(), [](double x) {
std::cout << "hello!"
x += bar()/(1+bar());
std::cout << x << " ";
});
I've written some several hundred line lambdas.
If you prefer, you can name your lambda separately with auto:
auto const baz = [](double x)
{
std::cout << "hello!"
x += bar()/(1+bar());
std::cout << x << " ";
};
std::for_each(foo.begin(), foo.end(), baz);
Hmm...
for_each(foo.begin(), foo.end(),
[] (double x)
{
std::cout << "hello!"
x += bar()/(1+bar());
std::cout << x << " ";
});
for (auto x : foo)
{
std::cout << "hello!";
x += bar()/(1+bar());
std::cout << x << " ";
}
I like to look at lambdas as just another function declaration, and thus, follow the same conventions that I use for other functions, within reason:
// when lambdas are present, I break the enveloping method params
for_each(
foo.begin(),
foo.end(),
[] (double x)
// I also like to split the brackets, just like with any function
{
std::cout << "hello!"
x += bar()/(1+bar());
std::cout << x << " ";
}); // the closing parenthesis is left with the closing bracket
I'd say if the code for the lambda is more than one or perhaps two statements, it should be a separate named function.
Post mine
std::vector<int> a;
std::find_if(a.begin()
, a.end()
, [&](int i)
{
return i == 0;
});