In functional programming, what terminology is used to distinguish between avoiding modifying what a variable refers to, and avoiding modifying an object开发者_Python百科 itself?
For example, in Ruby,
name += title
avoids modifying the object previously referred to by name
, instead creating a new object, but regrettably makes name
refer to the new object, whereas
full_title = name + title
not only avoids modifying objects, it avoids modifying what name
refers to.
What terminology would you use for code that avoids the former?
Using a name to refer to something other than what it did in an enclosing/previous scope is known as "shadowing" that name. It is indeed distinct from mutation. In Haskell, for example I can write
return 1 >>= \x -> return (x + 1) >>= \x -> print x.
The x
that is printed is the one introduced by the second lambda, i.e., 2
.
In do notation this looks a bit more familiar:
foo = do
x <- return 1
x <- return (x + 1)
print x
As I understand it, Erlang forbids aliasing altogether.
However, I suspect that mathepic is right in terms of Ruby -- its not just shadowing the name but mutating some underlying obect. On the other hand, I don't know Ruby that well...
I think functional programming languages simply do not have any operators that destructively updates one of the source operands (is destructive update, perhaps, the term you're looking for?). A similar philosophy is seen in instruction set design: the RISC philosophy (increasingly used in even the x86 architecture, in the newer extensions) is to have three-operand instructions for binary operators, where you have to explicitly specify that the target operand is the same as one of the sources if you want destructive update.
For the latter, some hybrid languages (like Scala; the same terminologies are used in X10) distinguish between values (val
) and variables (var
). The former cannot be reassigned, the latter can. If they point to a mutable object, then of course that object itself can still be modified.
精彩评论