functionalplus
Functional Programming Library for C++. Write concise and readable C++ code.
Science Score: 44.0%
This score indicates how likely this project is to be science-related based on various indicators:
-
✓CITATION.cff file
Found CITATION.cff file -
✓codemeta.json file
Found codemeta.json file -
✓.zenodo.json file
Found .zenodo.json file -
○DOI references
-
○Academic publication links
-
○Committers with academic emails
-
○Institutional organization owner
-
○JOSS paper metadata
-
○Scientific vocabulary similarity
Low similarity (12.1%) to scientific vocabulary
Keywords
Repository
Functional Programming Library for C++. Write concise and readable C++ code.
Basic Info
- Host: GitHub
- Owner: Dobiasd
- License: bsl-1.0
- Language: C++
- Default Branch: master
- Homepage: http://www.editgym.com/fplus-api-search/
- Size: 2.69 MB
Statistics
- Stars: 2,225
- Watchers: 73
- Forks: 177
- Open Issues: 3
- Releases: 27
Topics
Metadata Files
README.md

FunctionalPlus
helps you write concise and readable C++ code.
Table of contents
- Introduction
- Usage examples
- Type deduction and useful error messages
- Tutorial
- Forward application and composition
- Finding the functions you need
- Performance
- Comparison with range-v3
- Requirements and Installation
Introduction
Great code should mostly be self-documenting, but while using C++ in reality you can find yourself dealing with low-level stuff like iterators or hand-written loops that distract from the actual essence of your code.
FunctionalPlus is a small header-only library supporting you in reducing code noise and in dealing with only one single level of abstraction at a time. By increasing brevity and maintainability of your code it can improve productivity (and fun!) in the long run. It pursues these goals by providing pure and easy-to-use functions that free you from implementing commonly used flows of control over and over again.
Say you have a list of numbers and are interested in the odd ones only.
```c++ bool isoddint(int x) { return x % 2 != 0; }
int main()
{
typedef vector
There are different possibilities to attain your goal. Some of them are:
write a (range based) for loop
c++ Ints odds; for (int x : values) { if (is_odd_int(x)) { odds.push_back(x); } }use
std::copy_iffrom the STLc++ Ints odds; std::copy_if(std::begin(values), std::end(values), std::back_inserter(odds), is_odd_int);use
keep_iffromFunctionalPlusc++ auto odds = fplus::keep_if(is_odd_int, values);
If you think version 3 could be the one most pleasant to work with, you might like FunctionalPlus.
And if you still think the hand-written for loop is easier to understand, also consider what would happen if the loop body (i.e. a corresponding lambda function in the call to fplus::keep_if) would be much longer. When reading keep_if you would still immediately know that odds can only contain elements that came from values and were selected by some, possibly complicated, predicate. In the for loop case you have no idea what is happening until you read the whole loop body. The loop version probably would need a comment at the top stating what the use of keep_if would tell at first glance.
Usage examples
Below are some short examples showing nice things you can do with functions and containers using FunctionalPlus.
The same old song
You can test the content of a container for various properties, e.g. ```c++
include
include
int main() { std::liststd::string things = {"same old", "same old"}; if (fplus::allthesame(things)) std::cout << "All things being equal." << std::endl; } ```
The I in our team
There also are some convenience functions for retrieving properties of containers. For example you can count the occurrences of a character in a string. ```c++
include
include
int main() { std::string team = "Our team is great. I love everybody I work with."; std::cout << "There actually are this many 'I's in team: " << fplus::count("I", fplus::split_words(false, team)) << std::endl; } ```
Output:
There actually are this many 'I's in team: 2
The cutest kitty
Finding the highest rated element in a container is very simple compared to a hand-written version(1, 2). ```c++
include
include
struct cat { double cuteness() const { return softness_ * temperature_ * roundness_ * furamount - size; } std::string name; double softness; double temperature; double size; double roundness; double furamount; };
void main()
{
std::vector
auto cutest_cat = fplus::maximum_on(std::mem_fn(&cat::cuteness), cats);
std::cout << cutest_cat.name_ <<
" is happy and sleepy. *purr* *purr* *purr*" << std::endl;
} ```
Output:
Muffin is happy and sleepy. *purr* *purr* *purr*
Function composition, binding, and map creation
Let's say you have the following function given.
c++
std::list<int> collatz_seq(int x);
And you want to create an std::map<std::uint64_t, std::string> containing string representations of the Collatz sequences for all numbers below 30. You can implement this nicely in a functional way too.
```c++
include
include
// std::liststd::uint64_t collatzseq(std::uint64t x) { ... }
int main()
{
typedef std::list
// [1, 2, 3 ... 29]
auto xs = fplus::numbers<Ints>(1, 30);
// A function that does [1, 2, 3, 4, 5] -> "[1 => 2 => 3 => 4 => 5]"
auto show_ints = fplus::bind_1st_of_2(fplus::show_cont_with<Ints>, " => ");
// A composed function that calculates a Collatz sequence and shows it.
auto show_collats_seq = fplus::compose(collatz_seq, show_ints);
// Associate the numbers with the string representation of their sequences.
auto collatz_dict = fplus::create_map_with(show_collats_seq, xs);
// Print some of the sequences.
std::cout << collatz_dict[13] << std::endl;
std::cout << collatz_dict[17] << std::endl;
} ```
Output:
[13 => 40 => 20 => 10 => 5 => 16 => 8 => 4 => 2 => 1]
[17 => 52 => 26 => 13 => 40 => 20 => 10 => 5 => 16 => 8 => 4 => 2 => 1]
The functions shown not only work with default STL containers like std::vector, std::list, std::deque, std::string etc. but also with custom containers providing a similar interface.
Type deduction and useful error messages
FunctionalPlus deduces types for you where possible. Let's take one line of code from the Collatz example:
c++
auto show_collats_seq = fplus::compose(collatz_seq, show_ints);
collatz_seq is a function taking an uint64_t and returning a list<uint64_t>. show_ints takes a list<uint64_t> and returns a string. By making use of function_traits, written by kennyim, it is possible to automatically deduce the expression fplus::compose(collatz_seq, show_ints) as being a function taking an uint64_t and returning a string, so you do not have to manually provide type hints to the compiler.
If two functions whose "connecting types" do not match are passed in, an unambiguous error message describing the issue will be generated. FunctionalPlus uses compile time assertions to avoid the confusingly long error messages compilers generate when faced with type errors in function templates.
Changing the way you program from "writing your own loops and nested ifs" to "composing and using small functions" will result in more errors at compile time but will pay out by having fewer errors at runtime. Also, more precise compile-time errors will reduce the time spent debugging.
Tutorial
The article "Functional programming in C++ with the FunctionalPlus library; today: HackerRank challenge Gemstones" provides a smooth introduction into the library by showing how one could develop an elegant solution to a problem using the FunctionalPlus approach.
Also on Udemy there is a course "Functional Programming using C++" that makes heavy use of FunctionalPlus to explain general functional concepts.
Forward application and composition
The "Gemstones" tutorial above explains how one can apply functional thinking to arrive at the solution below for the following problem:
Find the number of characters present in every line of an input text.
```c++ std::string gemstone_count(const std::string& input) { using namespace fplus;
typedef std::set<std::string::value_type> characters;
const auto lines = split_lines(false, input); // false = no empty lines
const auto sets = transform(
convert_container<characters, std::string>,
lines);
// Build the intersection of all given character sets (one per line).
const auto gem_elements = fold_left_1(
set_intersection<characters>, sets);
return show(size_of_cont(gem_elements));
} ```
By using the functionality from namespace fwd, you can get along without temporary variables, and make it clear that the whole process is simply pushing the input through a chain of functions, similar to the pipe concept in the Unix command line.
c++
std::string gemstone_count_fwd_apply(const std::string& input)
{
using namespace fplus;
typedef std::set<std::string::value_type> characters;
return fwd::apply(
input
, fwd::split_lines(false)
, fwd::transform(convert_container<characters, std::string>)
, fwd::fold_left_1(set_intersection<characters>)
, fwd::size_of_cont()
, fwd::show()
);
}
In fplus::fwd:: you find many fplus:: functions again, but in a partially curried version, i.e. fplus::foo : (a, b, c) -> d has its counterpart with fplus::foo : (a, b) -> (c -> d). This makes the style above possible.
Alternatively to the forward application version, you can also write point-free and define your function by composition:
```c++ using namespace fplus; typedef std::setstd::string::value_type characters;
const auto gemstonecountfwdcompose = fwd::compose(
fwd::splitlines(false),
fwd::transform(convertcontainer
By the way, in case you need the parameters of a binary function in reverse order, namespace fplus::fwd::flip also exists. fplus::bar : (a, b) -> c does not only have its analog in fplus::fwd::bar : a -> b -> c but also in fplus::fwd::flip::bar : b -> a -> c.
Finding the functions you need
If you are looking for a specific FunctionalPlus function you do not know the name of yet, you can of course use the auto-complete feature of your IDE to browse the content of the namespace fplus. But the recommended way is to use the FunctionalPlus API search website. You can quickly search by keywords or function type signatures with it. If you prefer, you can also browse the source code using Sourcegraph.
Performance
The basic functions are fast, thanks to C++'s concept of abstraction without overhead. Here are some measurements from the first example, taken on a standard desktop PC, compiled with GCC and the O3 flag.
```
5000 random numbers, keep odd ones, 20000 consecutive runs accumulated
| Hand-written for loop | std::copyif | fplus::keepif | |-----------------------|--------------|----------------| | 0.632 s | 0.641 s | 0.627 s | ```
So the compiler seems to do a very good job optimizing and inlining everything to basically equal machine code performance-wise.
The more complex functions though sometimes could be written in a more optimized way. If you use FunctionalPlus in a performance-critical scenario and profiling shows you need a faster version of a function please let me know or even help improving FunctionalPlus.
FunctionalPlus internally often can operate in-place if a given container is an r-value (e.g. in chained calls) and thus avoids many unnecessary allocations and copies. But this is not the case in all situations. However, thanks to working with a multi-paradigm language one easily can combine manually optimized imperative code with fplus functions. Luckily experience (aka. profiling) shows that in most cases the vast majority of code in an application is not relevant for overall performance and memory consumption. So initially focusing on developer productivity and readability of code is a good idea.
Comparison with range-v3
FunctionalPlus and range-v3 (basis for ranges in C++-20) do have things in common, as the following code snippet shows.
```c++ const auto times3 = {return 3 * i;}; const auto isoddint = {return i % 2 != 0;}; const auto asstringlength = {return std::tostring(i).size();};
// FunctionalPlus using namespace fplus; const auto resultfplus = fwd::apply( numbers(0, 15000000) , fwd::transform(times3) , fwd::dropif(isoddint) , fwd::transform(asstring_length) , fwd::sum());
// range-v3 const auto resultrangev3 = accumulate( views::ints(0, ranges::unreachable) | views::take(15000000) | views::transform(times3) | views::removeif(isoddint) | views::transform(asstringlength), 0); ```
There are some differences though. Range-v3 ranges are lazy, which means no intermediate memory is allocated during the single steps of a processing chain like the above. When using FunctionalPlus on the other hand you work with normal STL containers. Also implementing a new function is simpler compared to writing a new range adaptor. Additionally FunctionalPlus provides much more functions out of the box and has the API search website. So the choice between the two libraries depends on your preferences and the project's needs.
Requirements and Installation
A C++14-compatible compiler is needed. Compilers from these versions on are fine: * GCC ( >= 4.9 ) * Clang ( >= 3.7 with libc++ >= 3.7 ) * Visual Studio ( >= 2015 ) * XCode ( >= 9 )
Guides for different ways to install FunctionalPlus can be found in INSTALL.md.
Disclaimer
The functionality in this library initially grew due to my personal need for it while using C++ regularly. I try my best to make it error-free and as comfortable to use as I can. The API still might change in the future. If you have any suggestions, find errors, miss some functions, or want to give general feedback/criticism, I'd love to hear from you. Of course, contributions are also very welcome.
License
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE or copy at
http://www.boost.org/LICENSE10.txt)
Owner
- Name: Tobias Hermann
- Login: Dobiasd
- Kind: user
- Location: Germany
- Website: https://www.linkedin.com/in/t-hermann/
- Repositories: 29
- Profile: https://github.com/Dobiasd
Loving functional programming, machine learning, and neat software architecture.
Citation (CITATION.cff)
cff-version: 1.2.0
title: "FunctionalPlus"
url: "https://github.com/Dobiasd/FunctionalPlus/"
authors:
- family-names: "Hermann"
given-names: "Tobias"
orcid: "https://orcid.org/0009-0007-4792-4904"
GitHub Events
Total
- Issues event: 2
- Watch event: 117
- Member event: 1
- Issue comment event: 24
- Push event: 14
- Pull request event: 17
- Fork event: 10
- Create event: 4
Last Year
- Issues event: 2
- Watch event: 117
- Member event: 1
- Issue comment event: 24
- Push event: 14
- Pull request event: 17
- Fork event: 10
- Create event: 4
Committers
Last synced: 9 months ago
Top Committers
| Name | Commits | |
|---|---|---|
| Dobiasd | e****m@g****m | 572 |
| Dobiasd | h****y@d****e | 525 |
| Théo DELRIEU | d****o@g****m | 137 |
| offa | b****v@y****m | 136 |
| Pascal Thomet | p****t@g****m | 58 |
| friendlyanon | f****n | 53 |
| Pascal Thomet | p****t@i****m | 25 |
| Unix&Me | u****e@g****m | 15 |
| Artalus | a****l@y****u | 9 |
| Ruan E. Formigoni | r****i@g****m | 8 |
| xtofl | k****d@g****m | 5 |
| Paiva | g****a@g****m | 5 |
| CrikeeIP | n****g@a****e | 4 |
| David Hirvonen | d****n@e****m | 4 |
| Patryk Małek | m****k@g****m | 3 |
| Tom Lin | t****6@g****m | 3 |
| danimtb | d****e@g****m | 3 |
| scinart | a****j@g****m | 3 |
| KYUNG MO KWEON | k****n@g****m | 3 |
| Paul | p****2@y****m | 2 |
| ferdymercury | f****y | 2 |
| bp | b****e@g****m | 2 |
| Seeker | m****g@p****m | 2 |
| A. Jiang | d****4@l****n | 1 |
| Adeel | a****m@o****m | 1 |
| Dillon Flamand | d****d | 1 |
| Henry Schreiner | H****I@g****m | 1 |
| Joshua Chia | j****a@g****m | 1 |
| Kvaz1r | a****m@y****u | 1 |
| Martin Horský | m****n@h****e | 1 |
| and 7 more... | ||
Committer Domains (Top 20 + Academic)
Issues and Pull Requests
Last synced: 4 months ago
All Time
- Total issues: 50
- Total pull requests: 93
- Average time to close issues: about 1 month
- Average time to close pull requests: 3 days
- Total issue authors: 23
- Total pull request authors: 16
- Average comments per issue: 3.94
- Average comments per pull request: 2.71
- Merged pull requests: 84
- Bot issues: 0
- Bot pull requests: 0
Past Year
- Issues: 4
- Pull requests: 10
- Average time to close issues: 3 days
- Average time to close pull requests: 5 days
- Issue authors: 3
- Pull request authors: 4
- Average comments per issue: 8.75
- Average comments per pull request: 1.3
- Merged pull requests: 9
- Bot issues: 0
- Bot pull requests: 0
Top Authors
Issue Authors
- Dobiasd (12)
- pthom (6)
- offa (4)
- tom91136 (3)
- friendlyanon (3)
- ander335 (2)
- jchia (2)
- ferdymercury (2)
- jmaldon1 (2)
- tbreslein (1)
- nblog (1)
- SEEYOU20 (1)
- lizhuimu (1)
- YannickLecroart (1)
- ruanformigoni (1)
Pull Request Authors
- offa (34)
- Dobiasd (32)
- pthom (14)
- friendlyanon (8)
- unixnme (3)
- LuSo58 (3)
- tom91136 (2)
- ferdymercury (2)
- frederick-vs-ja (2)
- tocic (1)
- am11 (1)
- moowlf (1)
- Adela0814 (1)
- ruanformigoni (1)
- mattpaletta (1)
Top Labels
Issue Labels
Pull Request Labels
Packages
- Total packages: 6
- Total downloads: unknown
-
Total dependent packages: 1
(may contain duplicates) -
Total dependent repositories: 107
(may contain duplicates) - Total versions: 79
proxy.golang.org: github.com/dobiasd/functionalplus
- Documentation: https://pkg.go.dev/github.com/dobiasd/functionalplus#section-documentation
- License: bsl-1.0
-
Latest release: v0.2.25
published over 1 year ago
Rankings
proxy.golang.org: github.com/Dobiasd/FunctionalPlus
- Documentation: https://pkg.go.dev/github.com/Dobiasd/FunctionalPlus#section-documentation
- License: bsl-1.0
-
Latest release: v0.2.25
published over 1 year ago
Rankings
vcpkg.io: fplus
Functional Programming Library for C++. Write concise and readable C++ code
- Homepage: https://github.com/Dobiasd/FunctionalPlus
- License: BSL-1.0
- Status: removed
-
Latest release: 0.2.22
published almost 2 years ago
Rankings
conda-forge.org: functionalplus
FunctionalPlus helps you write concise and readable C++ code.
- Homepage: https://github.com/Dobiasd/FunctionalPlus
- License: BSL-1.0
-
Latest release: 0.2.18
published about 4 years ago
Rankings
spack.io: functionalplus
Functional Programming Library for C++. Write concise and readable C++ code.
- Homepage: https://github.com/Dobiasd/FunctionalPlus
- License: []
-
Latest release: 0.2.25
published 7 months ago
Rankings
formulae.brew.sh: functionalplus
Functional Programming Library for C++
- Homepage: https://github.com/Dobiasd/FunctionalPlus
- License: BSL-1.0
-
Latest release: 0.2.25
published over 1 year ago