Live data from Hacker News

Haskell's effect on my C++ : exploit the type system

vallettaventures.com

41–50 of 57 posts

Re: Haskell's effect on my C++ : exploit the type system

#41
post #23

> int a = f(); > if (a > has been replaced with > const int a = MAX(0,f()); Going by MAX capitalization, it must be a macro, in which case the code is wrong. I am guessing this is a synthetic example, but still - try and get the basics right.

With GCC specifics, you can define MAX as a macro without calling the function twice.

  #define max(a,b) \
        ({ typeof (a) _a = (a); \
        typeof (b) _b = (b); \
        _a > _b ? _a : _b; })

Re: Haskell's effect on my C++ : exploit the type system

#42

My somewhat biased stance: functional programming languages make you progress as a programmer quickly. Becoming great requires deliberate practice and intrinsically hard problems. So you learn programming and CS about 5-10 times as fast in a functional language. This is part of why enterprise Java/C++ devs plateau at a skill level of 1.2 (even into their gray-haired years) while ML and Haskell programmers can reach 1…

I agree with one side of your message. There are very few people who have just learnt functional programming. I have met a few in academia, and they tend to be as "bad" as the pure Java/C++ programmers, but in a different way. They have trouble understanding how their code will boil down to CPU instructions, and so have trouble with performance, particularly (unsuprisingly) mutating algorithms, which are vital for pe…

To make it clear, I don't mean to rag on C, which is a great mid-level language. It's the ++ that I hate. Assembly is infantry: can do a lot of fine-grained work, but limited to about 5 mph with equipment. C is a tank-- a pretty powerful and impressive machine. It can shoot on the run and do 50 mph off-road. High-level languages are airplanes, perfect at 500 mph but coarse-grained from an operational standpoint. C++ exists because someone saw a tank and a plane and said, "I'm going to put wings on a fucking tank and see what happens." Thus, the tank-plane was born. The wings destroy its maneuverability on the ground and the weight of the tank makes it a shitty plane, and it looks fucking ridiculous, but there you go. Java exists because someone else concluded that the problem with tank-planes was that people were trying to fly them too fast and built an equally ridiculous invention-- the tank-icopter.

After I have defined a high-performance algorithm, they often want to modify it to make it "more beautiful" (which means functional) and in the process destroy the performance.

That's annoying. They should understand the concept of interface as separate from implementation. Implementations are allowed to be (and sometimes should be) ugly if performance concerns merit it.

Besides, mutable state, intelligently used, isn't "ugly". A lot of programs are simpler and more attractive when mutable state is used. Mutable state just needs to be used with taste.

What really pisses me off about that behavior pattern is when the tinkering is unnecessary. If it's working code, then who cares? I'm a hard-core FP advocate but I write stateful programs all the time. I try to wrap them behind interfaces that are as functional as possible. I will use state in controlled ways when appropriate; I just don't want to impose it on other people.

I work on low-level algorithm design in A.I., where performance is everything and there are many interlocking, low-level and complex algorithms and data structures.

I think what makes C++ appropriate for your purposes is that once code is written to spec, it doesn't need to be maintained (except for performance optimizations). I'm guessing that (except possibly for some STL usage) you're actually C.

Where C++ and Java really drop the ball (legacy disasters) is when code has to be read more times than it is written. If your goal is to write fast software one time and, once it's working code, never need to look at it again, C++ is probably appropriate.

Re: Haskell's effect on my C++ : exploit the type system

#43
I can sympathize; I too use C++ by day, and have become increasingly bitter/jealous/frustrated as I've spent more time with Haskell by night.

To the point that, I've started writing several libraries that enable in C++ several of the features I miss most in Haskell. In particular, I've missed the natural syntax of higher order functions, e.g., currying and functional composition, as well as the pithy expressiveness of Prelude vs the STL. With C++11, we can have these things, and while Boost gives us a wealth of functionality, it's hardly the most natural (and lightweight) library.

fc (functional composition) (https://github.com/jdduke/fc) and fpcpp (functional programming with C++)(https://github.com/jdduke/fpcpp) are my recent (very much work-in-progress) efforts towards this end.

With fc, one can naturally compose functions, lambdas and function objects, e.g., given composable functions f, g, h, write auto fgh = f + g + h; or, auto fgh = compose(f, compose (h,g));, and then call it as fgh(a,b,c);

fpcpp enables syntax like

  let pi = [](unsigned samples) -> double {
      typedef std::pair point;
      let dxs = map([](const point& p) { return p.first*p.first + p.second*p.second; },
                    zip(take(samples, rand_range(-1.0,1.0)),
                        take(samples, rand_range(-1.0,1.0))));
      return 4.0 * filter([](double d) { return d 
In writing fc and fpcpp, I've actually become less and less concerned for the future of C++; having used a good number of the C++11 features available, I've regained a good deal of my passion for C++ programming. Really, C++ needs a more expansive and natural standard library, iterators are powerful but are NOT the answer.

Re: Haskell's effect on my C++ : exploit the type system

#44

Earlier quoted context omitted.

I agree with one side of your message. There are very few people who have just learnt functional programming. I have met a few in academia, and they tend to be as "bad" as the pure Java/C++ programmers, but in a different way. They have trouble understanding how their code will boil down to CPU instructions, and so have trouble with performance, particularly (unsuprisingly) mutating algorithms, which are vital for pe…

To make it clear, I don't mean to rag on C, which is a great mid-level language. It's the ++ that I hate. Assembly is infantry: can do a lot of fine-grained work, but limited to about 5 mph with equipment. C is a tank-- a pretty powerful and impressive machine. It can shoot on the run and do 50 mph off-road. High-level languages are airplanes, perfect at 500 mph but coarse-grained from an operational standpoint. C++…

> C++ exists because someone saw a tank and a plane and said, "I'm going to put wings on a fucking tank and see what happens."

What a great metaphor. Hilarious, great imagery, and it's even mostly true!

Thanks for that, I'll remember it.

Re: Haskell's effect on my C++ : exploit the type system

#45
post #2

If your only example to show C++ verbosity fails to compile and is also patently wrong, you are not making a good point. (The constructor is private, the variable naming prevents short accessors such as Rectangle::width()). Better: struct Rectangle { double x,y, width, length; }; int main() { Rectangle r = {0., 0., 10., 10. }; return 0; } This even compiles in C++03. If you really insist on private members, you will…

If you replace Rectangle r with struct Rectangle r, your example even compiles in C89. :)

Re: Haskell's effect on my C++ : exploit the type system

#46
C++11 adopted strongly-typed enums, but I wish it also added strongly-typed typedefs. I've written (and found others') template classes to implement something similar, but the implementation is surprisingly (?) verbose and may introduce code bloat or runtime overhead. The compiler could implement this with no overhead!

C++11's strongly-typed enums look like:

  enum class Enumeration { Val1, Val2};
  enum class Enum2 : unsigned int {Val1, Val2};
A strongly-typed typedef could use similar "declare a class deriving from a native type" syntax:

  class Celcius : double;      // something like this?
  typedef Fahrenheit : double; // or maybe this?
  Celcius celcius = 0f;
  Fahrenheit fahrenheit = celcius; // ERROR

Re: Haskell's effect on my C++ : exploit the type system

#47

Earlier quoted context omitted.

I agree with one side of your message. There are very few people who have just learnt functional programming. I have met a few in academia, and they tend to be as "bad" as the pure Java/C++ programmers, but in a different way. They have trouble understanding how their code will boil down to CPU instructions, and so have trouble with performance, particularly (unsuprisingly) mutating algorithms, which are vital for pe…

To make it clear, I don't mean to rag on C, which is a great mid-level language. It's the ++ that I hate. Assembly is infantry: can do a lot of fine-grained work, but limited to about 5 mph with equipment. C is a tank-- a pretty powerful and impressive machine. It can shoot on the run and do 50 mph off-road. High-level languages are airplanes, perfect at 500 mph but coarse-grained from an operational standpoint. C++…

Thanks for your reply, it was very interesting.

One small comment - what makes C++ appropriate for my usage is mainly templates. Lots and lots of templates.

It is very useful to be able to easily compile an algorithm for different types. If compiling a whole 10,000+ line algorithm 4 times for char/short/int/long inputs with templates and doing run-time branching between the algorithms (but not in the algorithms) saves 15% CPU time, then that is well worth the work. I don't know (well) any other language that offers that. Obviously if you introduce some kind of abstract base class / interface like Java, you will immediately lose the benefit of going int -> short -> char, when a class is alway at least... 12 bytes? 16?)

In C doing that requires a lot of macros and rapidly gets unusable, in Java it requires introducing lots of interfaces and hoping things get inlined.

What I like about C++ (compared again to Java/C, not Haskell), is that I can without fear of cost (other than compile time) introduce another layer of abstraction. When benchmarking code this is amazing, I can easily swap in a vector, or a deque, or an optimised fixed-size stack array.

In Java it is common for people to 'un-Java' code, introducing arrays of primitives instead of arrays of classes for example.

I don't know how well Haskel does at that kind of thing.

Re: Haskell's effect on my C++ : exploit the type system

#48

Earlier quoted context omitted.

To make it clear, I don't mean to rag on C, which is a great mid-level language. It's the ++ that I hate. Assembly is infantry: can do a lot of fine-grained work, but limited to about 5 mph with equipment. C is a tank-- a pretty powerful and impressive machine. It can shoot on the run and do 50 mph off-road. High-level languages are airplanes, perfect at 500 mph but coarse-grained from an operational standpoint. C++…

Thanks for your reply, it was very interesting. One small comment - what makes C++ appropriate for my usage is mainly templates. Lots and lots of templates. It is very useful to be able to easily compile an algorithm for different types. If compiling a whole 10,000+ line algorithm 4 times for char/short/int/long inputs with templates and doing run-time branching between the algorithms (but not in the algorithms) save…

I think C++'s template feature is pretty unusual in languages. Lisps have macros, which are much more fully-featured and more hygienic than C macros, but I don't think any Lisps are fast enough to be interesting to you. I know that the Scala community is working on putting macros in.

Have you looked at Ocaml and Scala? Those might be close enough to suit your needs, and I think it's only a matter of time before Scala (or something like it) starts outperforming C++ on parallel problems.

What I'll say for C++ is that, in the style of development you're doing, it's definitely faster. The problem I have with C++ is all the use of it that occurs where it's not appropriate and actually makes performance worse because per unit time, programmers can accomplish less in it.

It's clearly possible for expert programmers to optimize the hell out of C++ in a way that just doesn't exist in GC languages, but I don't think average-case code is better, especially if it's framed as an economic problem and programmers of equivalent skill are involved and given the exact same amount of time to do it. Under those constraints, for a large problem, I would bet on Ocaml and Scala winning just because the programmers would have more time to spend on optimization. For a small problem, though, I'd bet on C++.

Re: Haskell's effect on my C++ : exploit the type system

#49

My somewhat biased stance: functional programming languages make you progress as a programmer quickly. Becoming great requires deliberate practice and intrinsically hard problems. So you learn programming and CS about 5-10 times as fast in a functional language. This is part of why enterprise Java/C++ devs plateau at a skill level of 1.2 (even into their gray-haired years) while ML and Haskell programmers can reach 1…

We must have had very different experiences. I found Java to be a lot more limiting than C++, and I find them more different than similar. In C++ templates let you implement many interesting ideas in the language. The syntax would be verbose, but there is definitely a lot of room for experimentation. Smart pointers, for example, are a great concept implemented with templates and making C++ programming a lot easier than it used to be. In Java, switching to a different JVM language is pretty much the only choice if you want more power. And even these languages are constrained by JVM if what you actually want is performance and predictability. The main strength of C++ is how easy it is to "embed" C into the more performance critical parts of the code. All the high level concepts in C++ provide easily understandable and transparent tradeoffs and can be turned off if you need to go "low level". Not every system needs this, and there are many other ways to use C with higher level languages. But there are definitely situations where C++ will be the nicest choice.

Re: Haskell's effect on my C++ : exploit the type system

#50

Earlier quoted context omitted.

Thanks for your reply, it was very interesting. One small comment - what makes C++ appropriate for my usage is mainly templates. Lots and lots of templates. It is very useful to be able to easily compile an algorithm for different types. If compiling a whole 10,000+ line algorithm 4 times for char/short/int/long inputs with templates and doing run-time branching between the algorithms (but not in the algorithms) save…

I think C++'s template feature is pretty unusual in languages. Lisps have macros, which are much more fully-featured and more hygienic than C macros, but I don't think any Lisps are fast enough to be interesting to you. I know that the Scala community is working on putting macros in. Have you looked at Ocaml and Scala? Those might be close enough to suit your needs, and I think it's only a matter of time before Scala…

C++ template's aren't just unusual, they're unique among mainstream languages. They're C++'s secret weapon. These days, if you're not making heavy use of templates in your C++ code then you're using the wrong language. Like you said, many people use C++ to solve problems they could be solving more quickly and more safely with another language, but it's not C++'s fault, it's their fault.

In particular, the key feature of C++ templates (as opposed to other similar systems of polymorphism) is that they abstract over not just code but data representation. This is what CJefferson was getting at and it's orthogonal to macros. Ocaml and Scala don't offer it. It's about data, not code, so you'll never be able to gloss over it with extra parallelism.

In C++ a std::pair really is just two doubles, 16 bytes. It can be passed into and returned from functions in registers. If I have a singly-linked list of them, each list cell is 24 bytes (16 for the pair, 8 for the next pointer.) In any other (mainstream) language, the pair is really a pair of pointers to boxed doubles which reside in the heap, and the list cell holds a pointer to that. The overhead of this is unacceptable in many situations, and these situations are where C++ still thrives. (cf. the Eigen linear algebra library for an example of "doing it right.")

Most languages have given up on this feature because of the drawbacks (code bloat) and the unified runtime representation of data (basically everything is a void*) makes many things easier (garbage collection, serialization, etc.) (I'm not super familiar with C# but I understand the struct types address this somewhat, but not without their own drawbacks.) But thanks to LLVM (written in C++ btw) people are pushing this area of language development forward (Rust, Deca, and others) in an attempt to fix the (many) problems of C++ while preserving its strengths.

Oh and BTW: A tank with wings is called an A-10 warthog :)

Post reply on HN