Created
July 19, 2024 03:45
-
-
Save leo-aa88/48ba4ebe9e144771bf18bf2f557844dd to your computer and use it in GitHub Desktop.
Functional C++ examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cassert> | |
#include <functional> | |
#include <algorithm> | |
class Callable { | |
public: | |
int operator()(int x) { return x + 1; }; | |
}; | |
const auto is_even = [](int x) -> bool | |
{ | |
return x % 2 == 0; | |
}; | |
std::function<int(int)> add_curried(int a) | |
{ | |
return [a](int b) | |
{ | |
return a + b; | |
}; | |
}; | |
template <typename T> | |
void print(T t) | |
{ | |
std::cout << t << std::endl; | |
} | |
int main(void) | |
{ | |
assert(is_even(2) == true); | |
assert(is_even(3) == false); | |
assert(is_even(4) == true); | |
Callable callable_object; | |
print(callable_object(1)); | |
int val = 42; | |
const auto add_value = [val](auto x) | |
{ | |
return x + val; | |
}; | |
print(add_value(1)); | |
print(add_value(1.1)); | |
print(add_curried(3)(4)); | |
std::vector<int> data{1, 2, 3, 4, 5}; | |
std::vector<int> results(data.size()); | |
std::transform(data.begin(), data.end(), results.begin(), [](int x) | |
{ return x + 1; }); | |
for (int num : results) | |
{ | |
print(num); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment