Category : monads

As per the title, I’d like to understand how to make std::vector an Applicative but not a Monad (well, not yet). This is just for the sake of exploring and understanding Boost.Hana and functional programming. Functor In hana/ext/std/vector.hpp, the Functor instance of std::vector is commented out, however, it seems to work fine (compiler explorer) if ..

Read more

I have a piece of code where I process a std::vector by splitting it into groups and processing each group. An if–else determines the processing each group undergoes: groups taking the if branch will end up giving a single ouptut, groups taking the else branch give rise to several outputs. All these outputs are collected ..

Read more

Let’s say that given a range like this std::vector<int> v{1, 4, 7, 2}; I want to generate another range where all even number are repeated a number of times equal to their value, whereas all odd numbers are left unchanged. A possible solution is the following: #include <iostream> #include <range/v3/view/join.hpp> #include <range/v3/view/transform.hpp> #include <range/v3/view/repeat_n.hpp> #include ..

Read more

Given this code, #include <iostream> #include <range/v3/view/join.hpp> #include <range/v3/view/repeat.hpp> #include <range/v3/view/take.hpp> #include <range/v3/view/transform.hpp> #include <utility> namespace rv = ranges::views; int main() { std::vector<int> v{0,1,2,3}; std::cout << (v | rv::transform([](int x){ return rv::repeat(x) | rv::take(x); }) | rv::join) << std::endl; // outputs [1,2,2,3,3,3] } I’d suppose there’s function that does the job combining join and transform ..

Read more

The type hana::optional represents an Optional value whose optional-ness is known at compile-time and it models, among others, the concept of Monad. Since it is a compile-time optional, the question of what happens at run-time if I try to hana::flatten a non-empty hana::optional which doesn’t wrap another hana::optional makes no sense, because because the error ..

Read more

The following dummy program compiles and runs #include <boost/range/adaptor/filtered.hpp> #include <boost/range/adaptor/transformed.hpp> #include <functional> #include <utility> #include <vector> using boost::adaptors::filtered; using boost::adaptors::transformed; auto whatever = [](auto&& x){ return std::forward<decltype(x)>(x); }; auto whenever = [](auto&){ return true; }; int main() { std::vector<int> v{1,2,3}; auto w1 = v | transformed(whatever); auto w2 = v | transformed(whatever) | filtered(whenever); ..

Read more