c++boost.gif (8819 bytes)HomeLibrariesPeopleFAQMore

8. Effects and thunks

FC++ is designed to be a library for pure functional programming. Nevertheless, this is C++, and it is reasonable to want to use effects. In this section, we describe how functoids with effects can be created.

There are three main ways to have effects inside an FC++ functoid:

We show examples of each in turn.

First, a global variable:

   struct some_functoid_type : public c_fun_type<int,int> {
      int operator()( int x ) const {
         std::cout << "Hello from inside some_functoid";
         return x;
      }
   } some_functoid;
   ...  some_functoid(4) ...
When the functoid is called, text appears on the standard output stream due to the effect on the global variable std::cout.

Second, using pointers:

   struct incr_type : public c_fun_type<int*,int> {
      int operator()( int* p ) const {
         return ++*p;
      }
   } incr;
   ...
   int x;
   ... incr( &x ) ...
Here the functoid manipulates the value of variable x through a pointer.

Finally, thunks:

   // building off last example
   fun0<int> f = thunk1( incr, &x );   // thunk that returns a higher 
   f(); f(); f();                  // integer each time it is invoked
In pure functional programming, there is no reason to ever have a zero-argument function (it would effectively be the same as a constant value). As a result, nullary functoids (thunks) almost always represent functoids which have some side-effect.

Last revised: October 03, 2003 at 23:27:22 GMTCopyright © 2000-2003 Brian McNamara and Yannis Smaragdakis