// optional monad in C++23: requires compiler that implements enough of // the 2023 standard. Compiled on M2 Mac with g++-13 -std=c++23. // The optional type was first introduced in 2017 but the important monadic // operations such as and_then and transform were not added until 2023. #include #include #include #include #include using namespace std; optional largest(vector& V) { if (V.size()==0) return nullopt; int max = V[0]; for(int i=1;imax) max = V[i]; } return max; // no "unit" constructor needed in C++ implementation. }//largest value in a vector, if it exists optional safediv(int a, int b) { if (b==0) return nullopt; else return a/b; }//safe div optional get_int_arg(int i, int argc, char **argv) { if ((i<0) || (i>=argc) || !argv) return nullopt; else return atoi(argv[i]); } int main(int argc, char** argv) { vector V{}; auto push = [&V](int x) mutable -> int {V.push_back(x); return 0;}; get_int_arg(1,argc,argv) .transform([&](auto x) mutable -> int { //transform = map V.push_back(x); return x; }); get_int_arg(2,argc,argv) .transform([&](auto x) mutable { V.push_back(x); return 0; }); largest(V) .and_then([](auto x){return safediv(100,x);}) // bind .transform([](auto x) { cout << "value is now " << x << endl; return 0; // dummy return }); return 0; }//main // There's another monad in C++23 called `expected`, which corresponds to // the `Result` monad found in other languages and which I implemented in // Java and C#.