4 ms·
Ruby has a nice convention where impure functions like those have a "!" appended to the name. For example String#gsub takes immutable string arguments and retur
by nonbirithm 6y ago
Ruby has a nice convention where impure functions like those have a "!" appended to the name. For example String#gsub takes immutable string arguments and returns a new string, but String#gsub! operates on a String instance and mutates it.
I guess if you write a new programming language, it would be nice to establish that convention early on, when it's still possible to be done.
- klipt 6y agoThat convention may have originated with Scheme, which has non mutating 'let' vs mutating 'set!'
- macintux 6y agoThe problem with Ruby’s approach, if I recall correctly (been 10 years) is that it’s inconsistent.
- ben-schaaf 6y agoThis is still true. Exclamation mostly means "this is dangerous". Array.push doesn't have an exclamation, and libraries like rails use it to signify that a method will throw an exception instead of return whether it succeeded.
- nonbirithm 6y agoActually I was thinking about how to determine function purity in a static analysis manner for a good while, spurred on by how the Chrome developer console sometimes gives "lazy previews" of typed Javascript statements, but only ones that have no side effects. As it turns out V8 has a feature which can guess if an expression is pure or impure, erring on the side of impure due to undecidability and other random issues. It does this by whitelisting a set of opcodes/built-ins that can potentially mutate state or not and running the statement in a separate VM instance with a debug hook set to throw an exception if an impure opcode/built-in is called. The parent developer tools code then prints the expression if the VM instance returns successfully. https://chromium.googlesource.com/v8/v8.git/+/ba5bac8cebe91c585024c67687ced8fe1baed833/src/debug/debug-evaluate.cc#267 https://chromium.googlesource.com/v8/v8.git/+/ba5bac8cebe91c... I wanted something similar in LuaJIT but it's pretty non-trivial to accomplish. I guess it's one of those mildly useful innovations you can only have with a lot of developer time.
- Animats 6y agoChecking for function purity is easier in some languages than others. It's mostly a transitive closure thing. Pure functions can call only pure functions. It's tough in Javascript, because function declaration is dynamic and you can rebind. It's not that tough in a more static language, where you can tell who calls whom at compile time. Way too many years ago, I did that.[1], starting at line 204. Knowing that a function is pure has many uses. You can optimize, using that x=y => f(x)=f(y). Pure functions can safely be used in assertions and conditional debug code. [1] https://github.com/John-Nagle/pasv/blob/master/src/CPC2/p2trutil.i https://github.com/John-Nagle/pasv/blob/master/src/CPC2/p2tr...