0

In functional programming, what terminology is used to distinguish between avoiding modifying what a variable refers to, and avoiding modifying an object 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?

Community
  • 1
  • 1
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
  • Modifying a variable doesn't exist in a purely functional language, so I doubt you will get a useful answer here, aside from just 'functional programming'. I understand that the underlying object for `name` changes, but if we consider that its probably implemented as a pointer, then theres a change in pointer, which is a change in state. – alternative Mar 27 '11 at 23:34
  • 1
    In pure functional programming, you can't even do the former. In impure FP, assignment and definition/binding are often syntactically different. – Fred Foo Mar 27 '11 at 23:36

2 Answers2

1

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...

sclv
  • 38,665
  • 7
  • 99
  • 204
1

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.

michel-slm
  • 9,438
  • 3
  • 32
  • 31