Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the name of a [foo, bar] = ["foo", "bar"] feature?

I need to know a correct name for this cool feature that some languages provide.

FYI: In some languages it is possible to do a multiple assignments by assigning a structure of values to a structure of "variables". In the example in the question title it assigns "foo" to foo and "bar" to bar.

like image 510
tillda Avatar asked Oct 17 '10 03:10

tillda


1 Answers

It's generally called destructuring bind in functional languages (which don't have assignments) and destructuring assignment in imperative languages.

Some languages provide subsets of that feature and then call it something different. For example, in Python it works with Tuples, Lists or Sequences and is called Tuple unpacking, List unpacking or Sequence unpacking, in Ruby, it works with Arrays (or objects that are convertible to an array) and is called parallel assignment.

Destructuring bind can get arbitrarily complex. E.g. this (imaginary) bind

[Integer(a), b, 2, c] = some_array

would assign the first element of some_array to a, the second element to b and the fourth element to c, but only if the first element is an Integer, the third element is equal to 2 and the length is 4. So, this even incorporates some conditional logic.

Destructuring bind is a subset of more general pattern matching, which is a standard feature of functional languages like Haskell, ML, OCaml, F#, Erlang and Scala. The difference is that destructuring bind only lets you take apart a structure and bind its components to variables, whereas pattern matching also matches on values inside those structures and lets you make decisions and in particular lets you run arbitrary code in the context of the bindings. (You can see the above imaginary bind as half-way in between destructuring bind and pattern matching.)

Here's the classical example of a reverse function in an imaginary language, written using pattern matching:

def reverse(l: List): List {
  match l {
    when []              { return [] }
    when [first :: rest] { return (reverse(rest) :: first) }
  }
}
like image 118
Jörg W Mittag Avatar answered Dec 21 '22 23:12

Jörg W Mittag