|
Boost : |
From: David B. Held (dheld_at_[hidden])
Date: 2003-10-20 12:25:26
"Brian McNamara" <lorgon_at_[hidden]> wrote in message
news:20031020154041.GB4670_at_lennon.cc.gatech.edu...
> [...]
> It might be helpful to check out
> http://www.nomaware.com/monads/html/index.html
> and look at {Identity,Maybe,List,State} in Part II. The state
> monad, in particular, is one of the best motivating examples
> for monads, since it's so familiar.
Is it fair to say that a monad is essentially a generic algorithm?
I mean, take std::for_each(), for example:
for_each(begin, end, op)
{
while (begin != end) op(begin++);
}
Here, operator!= and operator++ are defined by the iterator
type, but that's just syntactic sugar. It would be just as possible
to pass them in as functors as well, and achieve the same
result. Even though begin and end are expected to be
iterator types, they could be any type at all that defines
operator!= and operator++ appropriately, just like the run-time
arguments to a monad have to be compatible with the
functions called.
What I don't understand is that if my understanding is more
or less correct, why monads are supposed to be so profound?
I guess they do provide more flexibility than C++ generic
algorithms, but do they do so in a way that is truly useful?
In your example, we have roughly the C++ equivalent:
template <typename R, typename T>
struct comp1
{ typedef T type; R operator()(T a) const { ... } };
template <typename R, typename T>
struct comp2
{ typedef T type; R operator()(T b) const { ... } };
template <typename R, typename T>
struct comp3
{ typedef T type; R operator()(T c) const { ... } };
template <typename R, typename T1, typename T2, typename T3>
R f(T1 a, T2 b, T3 c)
{ ... }
template <typename R, typename M1, typename M2, typename M3>
R m_r(typename M1::type a, typename M2::type b,
typename M3::type c, M1 m1, M2 m2, M3 m3)
{
return f(m1(a), m2(b), m3(c));
}
Is my understanding close? Obviously, the Haskell version is
a bit shorter and more elegant. On the other hand, I can't think
of any practical situations where this level of abstraction is
more useful than writing the code out by hand, but maybe that's
just because I'm biased by the way C++ is written in the first
place.
Dave
--- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.521 / Virus Database: 319 - Release Date: 9/23/2003
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk