News for hackers. Stuff that matters.
Re:Functional programming in C++ by cousin_it on Monday September 26, 2016 @11:53AM (#12582852)
Quick and dirty imperative version:

    #include <climits>

    int count_common_chars(const std::string& str) {
      int n = 0, common = 0, counts[CHAR_MAX - CHAR_MIN + 1] = {};
      for (char c : str) {
        if (c == '\n') {
          common = 0;
          n++;
        }
        if (counts[c - CHAR_MIN] == n) {
          counts[c - CHAR_MIN]++;
          common++;
        }
      }
      return common;
    }
Tastes may vary, but to my eyes the imperative version has some advantages:

* Faster

* No allocations

* No dependencies

* Easy to add an early return if common == 0 (in the functional version it's much harder)

Re:Functional programming in C++ by tzs on Monday September 26, 2016 @01:36PM (#12583841)
> counts[CHAR_MAX - CHAR_MIN]

Shouldn't that be counts[CHAR_MAX - CHAR_MIN + 1] ?

Re:Functional programming in C++ by cousin_it on Monday September 26, 2016 @01:45PM (#12583928)
Good catch, thanks!
Re:Functional programming in C++ by anthay on Tuesday September 27, 2016 @04:16PM (#12592751)
That's cool and I agree about the advantages you mention.

In your code \n must be a line separator rather than a line terminator. (Otherwise, if the last line is \n terminated, the function returns 0.)

Re:Functional programming in C++ by cousin_it on Tuesday September 27, 2016 @05:09PM (#12593238)
Yeah, fair point.