Jump to content

Assignment (computer science)

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Josevalim (talk | contribs) at 16:22, 25 April 2011 (→‎Single assignment: Assignments does not necessarily introduce side effects. Side effects will only appear if you have global variables or if you have mutable closures.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, an assignment statement sets or re-sets the value stored in the storage location(s) denoted by a variable name. In most imperative computer programming languages, assignment statements are one of the basic statements. Common notations for the assignment operator are = and :=.[1]

Assignment statements typically allow for the same variable name to contain different values at different times during program execution. Thus a language with assignments does not have referential transparency which requires a procedure to return the same results for a given set of inputs at any point in time.

Semantics

An assignment operation is a process in imperative programming in which different values are associated with a particular variable name as time passes.[2] The program, in such model, operates by changing its state using successive assignment statements.[1][3] Primitives of imperative programming languages rely on assignment to do iteration.[4] At the lowest level, assignment is implemented using machine operations such as MOVE or STORE.[1][4]

The variables are containers for values. It is possible to put a value into variable and latter replace it with a new one. An assignment operation modifies the current state of the executing program.[3] Consequently, assignment is dependent on the concept of variables. In an assignment:

  • The expression is evaluated in the current state of the program.
  • The variable is assigned the computed value, replacing the prior value of that variable.

Example: Assuming that a is a numeric variable, the assignment a := 2*a means that the content of the variable a is doubled after the execution of the statement. The case that the assigned value depends on previous one is so common that many imperative languages, including C, C++, Java, and Python, augment the notion of assignment by defining special binary operators like *= for convenience so that the example becomes a *= 2.[3]

An example segment of C code:

int x = 10; 
float y;
x = 23;
y = 32.4;

In this sample, the variable x is first declared as an int, and is then assigned the value of 10. Notice that the declaration and assignment occur in the same statement. In the second line, y is declared without an assignment. In the third line, x is reassigned the value of 23. Finally, y is assigned the value of 32.4.

For an assignment operation, it is necessary that the value of the expression is well-defined (it is a valid rvalue) and that the variable represents a modifiable entity (it is a valid modifiable (non-const) lvalue). In some languages, such as Perl, it is not necessary to declare a variable prior to assigning it a value.

Single assignment

In pure functional programming, destructive assignment is not allowed, because of side effects[5]

Any assignment that changes an existing value (e.g. x := x + 1) is disallowed in purely functional languages. In functional programming, assignment is discouraged in favor of single assignment, also called name binding or initialization. Single assignment differs from assignment as described in this article in that it can only be made once, usually when the variable is created; no subsequent re-assignment is allowed. Once created by single assignment, named values are not variables but immutable objects.

An evaluation of expression does not have a side effect if it does not change an observable state of the machine,[6] and produces same values for same input.[4] While assignments does not necessarily introduce side effect, when used in conjunction with global variables[5] or mutable closures (i.e. modifying a variable inside the closure affects the binding where the closure was defined), assignments can introduce side effects while destroying and making the old value unavailable and substituting it with a new one. Some functional programming devotees use the derogatory term "destructive assignment" to refer to the imperative programming assignment operation.[3].

Single assignment is the only form of assignment available in purely functional languages, such as Haskell, which do not have variables in the sense of imperative programming languages.[4] The purely functional languages provide an opportunity for computation to be performed in parallel, avoiding von Neumann bottleneck of sequential one step at time execution, since values are independent of each other.[7] Impure functional languages provide both single assignment as well as true assignment (though true assignment is typically used with less frequency than in imperative programming languages). For example, in Scheme, both single assignment and true assignment can be used on all variables. In OCaml, only single assignment is allowed for variables, via the let name = value syntax; however, true assignment, by a separate <- operator, can be used on elements of arrays and strings, as well as fields of records and objects that have been explicitly declared mutable (meaning capable of being changed after its initial declaration) by the programmer.

Functional programming languages that use single assignment include Clojure, Erlang, F#, Haskell, Lava, Objective Caml, Oz, SASL, Scala (for vals), SISAL.

Value of an assignment

In most expression-oriented programming languages, the assignment statement returns the assigned value, allowing such idioms as x = y = a, which assigns the value of a to both x and y, and while (f = read()) {}, which uses the return value of a function to control a loop while assigning that same value to a variable.

In other programming languages, the return value of an assignment is undefined and such idioms are invalid. An example is Scheme.

In Python, assignment is a statement as opposed to an expression, and thus has no "value". However, chained assignment syntax is still supported.

In Haskell,[8] there is no variable assignment; but operations similar to assignment (like assigning to a field of an array or a field of a mutable data structure) usually evaluate to unit, the value of the unit type, which is typically the type of an expression that is evaluated purely for its side effects.

Parallel assignment

Some programming languages, such as JavaScript (since 1.7), occam 2,[9] Perl,[10] Python,[11] REBOL, Ruby,[12] and Windows PowerShell allow several variables to be assigned in parallel, with syntax like:

a,b := 0,1

which simultaneously assigns 0 to a and 1 to b. If the right-hand side of the assignment is an array variable, this feature is sometimes called sequence unpacking:

var list := {0, 1}
a,b := list

The list will be unpacked so that 0 is assigned to a and 1 to b. More interestingly,

a,b := b,a

Swaps the values of a and b. In languages without parallel assignment, this would have to be written to use a temporary variable

var t := a
a := b
b := t

since a:=b ; b:=a leaves both a and b with the original value of b.

Parallel assignment was introduced in CPL, in 1963, with the name 'simultaneous assignment'.[13]

Assignment versus equality

A notorious example for a bad idea was the choice of the equal sign to denote assignment. It goes back to Fortran in 1957 and has blindly been copied by armies of language designers. Why is it a bad idea? Because it overthrows a century old tradition to let “=” denote a comparison for equality, a predicate which is either true or false. But Fortran made it to mean assignment, the enforcing of equality. In this case, the operands are on unequal footing: The left operand (a variable) is to be made equal to the right operand (an expression). x = y does not mean the same thing as y = x.[14]

— Niklaus Wirth, Good Ideas, Through the Looking Glass

Beginning programmers sometimes confuse assignment with the relational operator for equality, as "=" means equality in mathematics, and is used for assignment in many languages. But assignment alters the value of a variable, while equality testing tests whether two expressions have the same value.

Many languages use different notation for each operation: for example, the assignment operator is a single equals sign ("=") while the equivalence operator is a pair of equals signs ("==") in C. But in some languages, such as BASIC, a single equals sign is used for both, with context determining which is meant.

This can lead to errors if the programmer forgets which form (=, ==, :=) is appropriate (or mistypes = when == was intended). This is a common programming problem with languages such as C, where the assignment operator also returns the value assigned, and can be validly nested inside expressions (in the same way that a function returns a value). If the intention was to compare two values in an if statement, for instance, an assignment is quite likely to return a value interpretable as TRUE, in which case the then clause will be executed, leading the program to behave unexpectedly. Some language processors (such as gcc) can detect such situations, and warn the programmer of the potential error.

Notation

Common textual representations of the assignment include an equals sign (=) and colon-equals (:=). These two forms are typical of programming languages (such as C), that classify assignment as an infix operator.

variable = expression BASIC, Bourne shell, C (and many of its descendants), Fortran, Java, PL/I, Python, Windows PowerShell...
variable := expression Ada, ALGOL, Dylan,[15] Eiffel,[16][17] Pascal[18]

Other possibilities include a left arrow or a keyword, though there are other, rarer, variants:

variable << expression Magik
variable <- expression Objective Caml, R, S
variableexpression APL[19]
variable =: expression J
LET variable = expression BASIC
set variable to expression AppleScript
set variable = expression C shell
Set-Variable variable (expression) Windows PowerShell
val variable = expression ML[20]
variable : expression Macsyma, Maxima

Some platforms put the expression on the left and the variable on the right:

MOVE expression TO variable COBOL
expressionvariable TI-BASIC, Casio BASIC
expression -> variable R

Some expression-oriented languages, such as Lisp[21][22] and Tcl, uniformly use prefix syntax for all statements, including assignment.

(setq variable expression) Lisp
(set! variable expression) Scheme[23][24][25]
set variable expression Tcl

See also

References

  1. ^ a b c Imperative Programming
  2. ^ Topics in Information Processing
  3. ^ a b c d Ruediger-Marcus Flaig (2008). Bioinformatics programming in Python: a practical course for beginners. Wiley-VCH. pp. 98–99. ISBN 9783527320943. Retrieved 25 December 2010.
  4. ^ a b c d Crossing borders: Explore functional programming with Haskell, by Bruce Tate
  5. ^ a b Imperative Programming Languages (IPL)
  6. ^ Mitchell, John C. (2003). Concepts in programming languages. Cambridge University Press. p. 23. ISBN 9780521780988. Retrieved 3 January 2011.
  7. ^ John C. Mitchell (2003). Concepts in programming languages. Cambridge University Press. pp. 81–82. ISBN 9780521780988. Retrieved 3 January 2011.
  8. ^ Hudak, Paul (2000). The Haskell School of Expression: Learning Functional Programming Through Multimedia. Cambridge: Cambridge University Press. ISBN 0-521-64408-9. {{cite book}}: Cite has empty unknown parameter: |coauthors= (help)
  9. ^ INMOS Limited, ed. (1988). Occam 2 Reference Manual. New Jersey: Prentice Hall. ISBN 0-13-629312-3. {{cite book}}: Cite has empty unknown parameter: |coauthors= (help)
  10. ^ Wall, Larry (1996). Perl Programming Language (2 ed.). Cambridge: O´Reilly. ISBN 1-56592-149-6. {{cite book}}: Unknown parameter |coauthors= ignored (|author= suggested) (help)
  11. ^ Lutz, Mark (2001). Python Programming Language (2 ed.). Sebastopol: O´Reilly. ISBN 0-596-00085-5. {{cite book}}: Cite has empty unknown parameter: |coauthors= (help)
  12. ^ Thomas, David (2001). Programming Ruby: The Pragmatic Programmer´s Guide. Upper Saddle River: Addison Wesley. ISBN 0-201-71089-7. {{cite book}}: Unknown parameter |coauthors= ignored (|author= suggested) (help)
  13. ^ D.W. Barron et al., "The main features of CPL", Computer Journal 6:2:140 (1963). full text (subscription)
  14. ^ Niklaus Wirth. "Good Ideas, Through the Looking Glass". Retrieved 2010-12-04.
  15. ^ Feinberg, Neal (1997). Dylan Programming. Massachusetts: Addison Wesley. ISBN 0-201-47976-1. {{cite book}}: Unknown parameter |coauthors= ignored (|author= suggested) (help)
  16. ^ Meyer, Bertrand (1992). Eiffel the Language. Hemel Hempstead: Prentice Hall International(UK). ISBN 0-13-247925-7. {{cite book}}: Cite has empty unknown parameter: |coauthors= (help)
  17. ^ Wiener, Richard (1996). An Object-Oriented Introduction to Computer Science Using Eiffel. Upper Saddle River, New Jersey: Prentice Hall. ISBN 0-13-183872-5. {{cite book}}: Cite has empty unknown parameter: |coauthors= (help)
  18. ^ Moore, Lawrie (1980). Foundations of Programming with Pascal. New York: John Wiley & Sons. ISBN 0-470-26939-1.
  19. ^ Iverson, Kenneth E. (1962). A Programming Language. John Wiley and Sons. ISBN 0471430145.
  20. ^ Ullman, Jeffrey D. (1998). Elements of ML Programming: ML97 Edition. Englewood Cliffs, New Jersey: Prentice Hall. ISBN 0-13-790387-1.
  21. ^ Graham, Paul (1996). ANSI Common Lisp. New Jersey: Prentice Hall. ISBN 0-13-370875-6.
  22. ^ Steele, Guy L. (1990). Common Lisp: The Language. Lexington: Digital Press. ISBN 1-55558-041-6.
  23. ^ Dybvig, R. Kent (1996). The Scheme Programming Language: ANSI Scheme. New Jersey: Prentice Hall. ISBN 0-13-454646-6.
  24. ^ Smith, Jerry D. (1988). Introduction to Scheme. New Jersey: Prentice Hall. ISBN 0-13-496712-7. {{cite book}}: Cite has empty unknown parameter: |coauthors= (help)
  25. ^ Abelson, Harold (1996). Structure and Interpretation of Computer Programs. New Jersey: McGraw-Hill. ISBN 0-07-000484-6. {{cite book}}: Unknown parameter |coauthors= ignored (|author= suggested) (help)

Template:Link GA