Hacker News new | ask | show | jobs
by Negitivefrags 4609 days ago
With regard to declaring the lack of side effects in an interface, I'd just like to mention that C++ is very nice in this regard too, and I think it's an important feature of C++ that is often overlooked.

Yes, it's true that with casting and so on you are not actually ensuring anything when you declare a function const like you are with Haskell, but you announce to other programmers who will use your code that:

1) There will be no observable state changes

2) That the function is thread safe

This is a very useful thing for a language to support in it's function declarations, and other languages could do well to learn from that.

2 comments

That is not true. In C++ you can always retrieve the current time, store parameters in a database, print to stdout, or retrieve a global variable without changing the interface. Merely announcing purity to other programmers does not solve this problem: announcements can be wrong, missing, incomplete, and maybe most importantly the compiler doesn't know about them.
Heck, mere "announcements" might even be quite useful, especially since it is slightly compiler supported. But const in C++ does not announce purity, nor does it announce thread-safety. I just announced that it won't observably change non-mutable members, that's it.
D actually has a better model for pure functions than C++. See http://dlang.org/function.html#pure-functions
Modern C/C++ compilers can detect a sub set of pure functions and do possible aggressive optimisations. There's even an `__attribute__ ((pure))` in GCC for explicit pureness.