views:

414

answers:

5

Can someone guide me how do functional programming in C++? Is there some good online material that I can refer?

Please note that I know about the library FC++. I want to know how to do that with C++ standard library alone.

Thanks.

+3  A: 

You can try FC++

Nemanja Trifunovic
Did you even read the question?
San Jacinto
@San Jacinto: the OP could have updated his question
Eli Bendersky
OMFG! Please stop downvoting that guy! It's not his fault! I updated my question 2 mins later!
Red Hyena
Don't worry. One upvote makes up for five downvotes. Literally.
Chuck
I don't see an "edited" timestamp.
San Jacinto
@San Jacinto: If you edit fast enough, it doesn't count as an edit.
Chuck
@chuck thanks for the info. wish i could remove my downvote now, but i don't know that he'll be missing the 2 points anyway.
San Jacinto
Hey, no big deal. Cheers.
Nemanja Trifunovic
Sorry to everyone! 'twas all my fault! :(
Red Hyena
+8  A: 

You can not do true functional programming with C++. All you can do is approximate it with a large amount of pain and complexity. Therefore, this approach isn't recommended. Why do you want to?

Eli Bendersky
Nothing. Just for fun. :)
Red Hyena
It's **NOT** fun programming FP in C++. For fun program FP with Lisp or Haskell
Eli Bendersky
I'd surely learn FP language someday. But now I don't have time for that.
Red Hyena
But I have to insist :-) It will take less time than learning how to do that in C++
Eli Bendersky
Okay. I'll check out some FP language. Thanks for the response!
Red Hyena
I don't think this is fair. Sure, you can't completely eschew side-effects in C++, but you can go a long way towards adopting a functional approach. Books like <a href="http://hop.perl.plover.com/">Higher Order Perl</a> show that functional approaches can be used in an imperative language. Moreover, various features of C++ make a functional style easier to adopt than in, say, C.
daf
@daf: Whether you can "go a long way toward adopting a functional approach" in C++, it's still not as well-supported as in a functional language. Nobody's even talking about completely eschewing side effects (the languages people are recommending, like OCaml and Scheme, are all impure). You can apply functional principles to C++ code, but it will be harder to learn those principles in the language. So I think this answer is closer than endorsing C++ as a functional language. And saying that it's easier to do than in C is pretty much damning with faint praise.
Chuck
So many times it has been said 'C++ can not do' in the past.. Even past STL style FP, you know the outcome. Go Phoenix that's the Spirit :)
rama-jka toti
I recommend scheme... it's one of the purest functional languages. You'll learn how to think functionally very quickly.
Mongoose
@daf: Perl is **far** from being an imperative language. It's a multi-paradigm language with first order functions that supports FP naturally
Eli Bendersky
+3  A: 

I don't think that you can't to true, real, functional programming in C++; but it's certainly not the easiest or natural way to use it. Also, you might just use a couple of functional-like idioms and not the whole mindset (i.e. 'fluent style')

My advise would be to learn a functional language, maybe start with Scheme, then move to Haskell. Then use what you've learned when programming in C++. maybe you won't use an obvious functional style; but you might get the biggest advantages (i.e. using immutable structures).

Javier
as someone learning haskell, I'd be interested in knowing why you suggest scheme first.
Evan Carroll
I have seen some Scheme code before. It looks like all Chinese-Japanese to me. :|
Red Hyena
Okay. I'll check out some FP language. Thanks for the response!
Red Hyena
@EvanCarroll: maybe it's just how i learned them; but i find Scheme less surprising. Also there's some good (but old) introductory texts for Scheme, not so many (or not so well known) for other FP languages
Javier
@Jacon Johnson: yeah, the first sight of a new syntax (or lack of) can be upsetting, but it's really skin deep. The real meat is underneath (but some are made easier by the lack of syntax). Still, there's nothing magical about Scheme, just pick any FP language that seems approachable.
Javier
+13  A: 

You can accomplish a surprising amount of "functional programming" style with modern C++. In fact, the language has been trending in that direction since its' standardization.

The standard library contains algorithms analogous to map, reduce, etc (for_each, transform, adjacent_sum...). The next revision, C++0x, contains many features designed to let programmers work with these in a more functional style (lambda expressions, etc.).

Look into the various Boost libraries for more fun. Just to illustrate that standard C++ contains plenty of functional goodness, here's a factorial function in continuation-passing style in standard C++.

#include <iostream>

// abstract base class for a continuation functor
struct continuation {
    virtual void operator() (unsigned) const = 0;
};

// accumulating continuation functor
struct accum_cont: public continuation {
    private:
        unsigned accumulator_;
        const continuation &enclosing_;
    public:
        accum_cont(unsigned accumulator, const continuation &enclosing)
            : accumulator_(accumulator), enclosing_(enclosing) {}; 
        virtual void operator() (unsigned n) const {
            enclosing_(accumulator_ * n);
        };
};

void fact_cps (unsigned n, const continuation &c)
{
    if (n == 0)
        c(1);
    else
        fact_cps(n - 1, accum_cont(n, c));
}

int main ()
{
    // continuation which displays its' argument when called
    struct disp_cont: public continuation {
        virtual void operator() (unsigned n) const {
            std::cout << n << std::endl;
        };
    } dc;

    // continuation which multiplies its' argument by 2
    // and displays it when called
    struct mult_cont: public continuation {
        virtual void operator() (unsigned n) const {
            std::cout << n * 2 << std::endl;
        };
    } mc;

    fact_cps(4, dc); // prints 24
    fact_cps(5, mc); // prints 240

    return 0;
}

Ok, I lied a little bit. It's a factorial functor. After all, closures are a poor man's objects... and vice versa. Most of the functional techniques used in C++ rely on the use of functors (i.e. function objects)---you'll see this extensively in the STL.

Derrick Turk
Nice example. But the choice of identifier names I must say is very bad, So if you could please edit your post and use some better identifier names. I have upvoted you by the way. Thanks! :)
Red Hyena
"After all, closures are a poor man's objects... and vice versa." i have to disagree. yes, you can implement one using the other... but what happens if you want to reimplement objects based on functors? a hideous mess. and if you reimplement closures on top of closure-based objects? it unravels itself (almost) to the 'native' concepts. Thus, i think closures are _far_ more appropriate as 'primitives' than objects (and don't get me started about class-based objects!)
Javier
Thanks, Jacob! I cleaned up the example a little bit. It was never intended for public display; I had just read Lambda: The Ultimate Imperative one day and wanted to try CPS in C++. But then I saw this question and just had to share...
Derrick Turk
@Javier: I know it's one of those equivalences that's not necessarily very important in practice (cf. Turing-equivalence). However, standard C++ is actually heading toward making "closures" more transparent (with objects, as far as I know, under the hood. Even with the current language functors are widely used to fulfill the same purposes as "first-class" closures.
Derrick Turk
+1  A: 

There is a book called Functional C by Pieter Hartel and Henk Muller which might help. If it still available. A link to some info on it is here. IIRC it wasn't too bad.

rvirding
According to the description, that book teaches imperative programming to people coming from functional languages. Not how to do functional programming in C (which would be quite a bit more painful than doing it in C++, I'd imagine).
sepp2k
Ostensibly this is so, but there is nothing to stop you using in the opposite direction. It works quite well for that and does give you some indications how to program C in a functional style.
rvirding