C++ are introducing monadic interfaces. We have compared hspp and some proposals, refer to std::optional and std::expected for more details.
Here you are!
The sample is originated from Learn You a Haskell for Great Good!
"Pierre has decided to take a break from his job at the fish farm and try tightrope walking. He's not that bad at it, but he does have one problem: birds keep landing on his balancing pole! Let's say that he keeps his balance if the number of birds on the left side of the pole and on the right side of the pole is within three."
Note that Pierre may also suddenly slip and fall when there is a banana.
Original Haskell version
routine :: Maybe Pole
routine = do
start <- return (0,0)
first <- landLeft 2 start
Nothing
second <- landRight 2 first
landLeft 1 second
C++ version using hspp
Id<Pole> start, first, second;
auto const routine = do_(
start <= return_ | Pole{0,0}),
first <= (landLeft | 2 | start),
nothing<Pole>,
second <= (landRight | 2 | first),
landLeft | 1 | second
);
In p0323r0, there is a proposal to add a utility class to represent expected monad.
A use case would be like
expected<int, error_condition> safe_divide(int i, int j)
{
if (j == 0) return make_unexpected(arithmetic_errc::divide_by_zero);
if (i%j != 0) return make_unexpected(arithmetic_errc::not_integer_division);
else return i / j;
}
// i / k + j / k
expected<int, error_condition> f(int i, int j, int k)
{
return safe_divide(i, k).bind([=](int q1)
{
return safe_divide(j,k).bind([=](int q2)
{
return q1+q2;
});
});
}
In hspp, the codes would be like
auto safe_divide(int i, int j) -> Either<arithmetic_errc, int>
{
if (j == 0) return toLeft | arithmetic_errc::divide_by_zero;
if (i%j != 0) return toLeft | arithmetic_errc::not_integer_division;
else return toRight || i / j;
}
auto f(int i, int j, int k) -> Either<arithmetic_errc, int>
{
Id<int> q1, q2;
return do_(
q1 <= safe_divide(i, k),
q2 <= safe_divide(j, k),
return_ || q1 + q2
);
}
Refer to proposal sample for complete sample codes.
Filter even numbers.
using namespace hspp;
using namespace hspp::doN;
Id<int> i;
auto const result = do_(
i <= std::vector{1, 2, 3, 4},
guard | (i % 2 == 0),
return_ | i
);
Obtain an infinite range of Pythagorean triples.
Haskell version
triangles = [(i, j, k) | k <- [1..], i <- [1..k], j <- [i..k] , i^2 + j^2 == k^2]
using namespace hspp::doN;
using namespace hspp::data;
Id<int> i, j, k;
auto const rng = _(
makeTuple<3> | i | j | k,
k <= (enumFrom | 1),
i <= (within | 1 | k),
j <= (within | i | k),
if_ || (i*i + j*j == k*k)
);
Equivalent version using RangeV3 would be link
using namespace ranges;
// Lazy ranges for generating integer sequences
auto const intsFrom = view::iota;
auto const ints = [=](int i, int j)
{
return view::take(intsFrom(i), j-i+1);
};
// Define an infinite range of all the Pythagorean
// triples:
auto triples =
view::for_each(intsFrom(1), [](int z)
{
return view::for_each(ints(1, z), [=](int x)
{
return view::for_each(ints(x, z), [=](int y)
{
return yield_if(x*x + y*y == z*z,
std::make_tuple(x, y, z));
});
});
});
We have two functions, plus1, and showStr. With do notation we construct a new function that will accept an integer as argument and return a tuple of results of the two functions.
auto plus1 = toFunc<> | [](int x){ return 1+x; };
auto showStr = toFunc<> | [](int x){ return show | x; };
Id<int> x;
Id<std::string> y;
auto go = do_(
x <= plus1,
y <= showStr,
return_ || makeTuple<2> | x | y
);
auto result = go | 3;
std::cout << std::get<0>(result) << std::endl;
std::cout << std::get<1>(result) << std::endl;
Original haskell version Monadic Parsing in Haskell
expr, term, factor, digit :: Parser Int
digit = do {x <- token (sat isDigit); return (ord x - ord '0')}
factor = digit +++ do {symb "("; n <- expr; symbol ")"; return n}
term = factor `chainl1` mulop
expr = term `chainl1` addop
C++ version parse_expr
Id<char> x;
auto const digit = do_(
x <= (token || sat | isDigit),
return_ | (x - '0')
);
extern TEParser<int> const expr;
Id<int> n;
auto const factor =
digit <alt>
do_(
symb | "("s,
n <= expr,
symb | ")"s,
return_ | n
);
auto const term = factor <chainl1> mulOp;
TEParser<int> const expr = toTEParser || (term <chainl1> addOp);
Transfer from one account to another one atomically.
Id<Account> from, to;
Id<Integer> v1, v2;
auto io_ = do_(
from <= (newTVarIO | Integer{200}),
to <= (newTVarIO | Integer{100}),
transfer | from | to | 50,
v1 <= (showAccount | from),
v2 <= (showAccount | to),
hassert | (v1 == 150) | "v1 should be 150",
hassert | (v2 == 150) | "v2 should be 150"
);
io_.run();
Withdraw from an account but waiting for sufficient money.
Id<Account> acc;
auto io_ = do_(
acc <= (newTVarIO | Integer{100}),
forkIO | (delayDeposit | acc | 1),
putStr | "Trying to withdraw money...\n",
atomically | (limitedWithdrawSTM | acc | 101),
putStr | "Successful withdrawal!\n"
);
io_.run();
And we can also compose two STMs with orElse
// (limitedWithdraw2 acc1 acc2 amt) withdraws amt from acc1,
// if acc1 has enough money, otherwise from acc2.
// If neither has enough, it retries.
constexpr auto limitedWithdraw2 = toFunc<> | [](Account acc1, Account acc2, Integer amt)
{
return orElse | (limitedWithdrawSTM | acc1 | amt) | (limitedWithdrawSTM | acc2 | amt);
};
Id<Account> acc1, acc2;
auto io_ = do_(
acc1 <= (atomically | (newTVar | Integer{100})),
acc2 <= (atomically | (newTVar | Integer{100})),
showAcc | "Left pocket" | acc1,
showAcc | "Right pocket" | acc2,
forkIO | (delayDeposit | acc2 | 1),
print | "Withdrawing $101 from either pocket...",
atomically | (limitedWithdraw2 | acc1 | acc2 | Integer{101}),
print | "Successful withdrawal!",
showAcc | "Left pocket" | acc1,
showAcc | "Right pocket" | acc2
);
io_.run();
using O = std::string;
using I = std::string;
// coroutine for handling strings
Id<std::string> name, color;
auto const example1 = do_(
name <= (yield<IO, O, I, std::string> | "What's your name? "),
lift<Producing, O, I> || putStrLn | ("Hello, " + name),
color <= (yield<IO, O, I, std::string> | "What's your favorite color? "),
lift<Producing, O, I> || putStrLn | ("I like " + color + ", too.")
);
auto const foreverKResult = foreverK | [](std::string str) -> Producing<IO, O, I, std::string>
{
return do_(
lift<Producing, O, I> || putStrLn | str,
(lift<Producing, O, I> | getLine) >>= yield<IO, O, I, std::string>
);
};
// coroutine for handling io
auto const stdOutIn = toConsumingPtr_<IO, O, I, _O_> || foreverKResult;
// let the two coroutines hand over control to each other by turn.
auto io_ = example1 <SS> stdOutIn;
io_.run();
The sample running would be like
> What's your name?
< Bob
> Hello, Bob
> What's your favorite color?
< Red
> I like Red, too.
Haskell | Hspp |
---|---|
function | Function / GenericFunction |
f x y | f | x | y |
f $ g x | f || g | x |
f . g $ x | f <o> g || x |
a `f` b | a <f> b |
[f x | x <- xs, p x] | _(f | x, x <= xs, if_ || p | x) |
list (lazy) | range |
list (strict) | std::vector/list/forward_list |
do {patA <- action1; action2} | do_(patA <= action1, action2) |
f <$> v | f <fmap> v |
f <*> v | f <ap> v |
pure a | pure | a |
m1 >> m2 | m1 >> m2 |
m1 >>= f | m1 >>= f |
return a | return_ | a |
The library is
- for fun,
- to explore the interesting features of Haskell,
- to explore the boundary of C++,
- to facilitate the translation of some interesting Haskell codes to C++.
This library is still in active development and not production ready.
Discussions / issues / PRs are welcome.
Haskell pattern matching is not covered in this repo. You may be interested in match(it) if you want to see how pattern matching works in C++.
Please star the repo, share the repo, or sponsor $1 to let me know this project matters.