3 ms·
I really like D's approach instead. A function declared pure can have no side effects but it can do whatever kind of mess it wants within its own code. It can h
by jordigh 9y ago
I really like D's approach instead. A function declared pure can have no side effects but it can do whatever kind of mess it wants within its own code. It can have loops, assignments, reassignments, memory allocations, but it can't mutate variables outside its scope nor can it call any impure functions. I find this is a very practical compromise that lets you have the good parts of purity without ever getting the urge to write a blog post about monads.
https://dlang.org/spec/function.html#pure-functions https://dlang.org/spec/function.html#pure-functions
- olavk 9y agoThis is definitely cool, but monads is a more general concept. It can be used to isolate side-effects, but can also be used for many other things.
- tome 9y agoThat's what Haskell calls "ST" and is far less powerful than the general notion of monads.
- quchen 9y agoHaskell has the ST type for this, which is a stripped version of IO in which we can still make proper mutable inplace updates like in other languages, but there is a »runner« function called »runST«, which guarantees that the computation it contains does not leak any state to the outside – in other words, »runST <impure>« is pure from the outside. This allows embedding of mutable algorithms, e.g. inplace sorting of vectors, into pure code.
- gowld 9y agoThis is "const" in c++
- jordigh 9y agoI don't think this is the same. My C++ is getting rusty, so correct me if I'm wrong, but making a function const is mostly about making the "this" pointer const. A const function can still mutate global variables or call non-const functions, such as operator<< on cout. A pure D function can do neither of those things.
- gowld 9y agoThat's fair. C++ has const methods on objects, but I think nothing at global scope. But you shouldn't have global mutable state :-)