Difference between revisions of "W1037 Expressions and Operators"

From Coder Merlin
(Replaced content with "{{MovedToMoodle|CS-151,Unit III,Chapters 6-7}}")
Tag: Replaced
 
(2 intermediate revisions by one other user not shown)
Line 1: Line 1:
[[File:The expression of the emotions in man and animals (1872) (14762147996).jpg|thumb|link=|The expression of the emotions in man and animals (1872)]]
{{MovedToMoodle|CS-151,Unit III,Chapters 6-7}}
== Prerequisites ==
* [[W1031 Positive Integers]]
* [[W1032 Negative Integers]]
* [[W1033 Character Encoding]]
* [[W1038 L-Values and R-Values]]
== Introduction ==
An '''expression''' is a finite series of symbols that is well-formed according to agreed upon rules.  The symbols may include '''constants''', '''variables''', '''operators''', and '''brackets'''.  A valid expression will yield a value of a specific type according to the rules of the language.
 
== Type Inference ==
=== Integers ===
All expressions, when evaluated, yield a particular '''type'''.  For example, in the expression:
<syntaxhighlight lang="swift">
let x = 3
</syntaxhighlight>
''x'' will be of type '''Int''', which is an integer whose size depends on the size of the underlying platform.  (On 32-bit platforms, Int will be equivalent to '''Int32''', and on 64-bit platforms, Int will be equivalent to '''Int64'''.)  On the other hand, in the expression:
<syntaxhighlight lang="swift">
let y = 3.0
</syntaxhighlight>
''y'' will be of type '''Double''', which is a double-precision, floating-point type.  '''Because Swift is a type-safe language, all expressions will always have a ''specific type'''''.  Type-safety enables the compiler to warn us when we make a mistake, such as by using an Int when we intended a Double.
Like many other type-safe languages, we're able to ''explicitly'' specify the type of a constant of variable:
<syntaxhighlight lang="swift">
let x : Int = 3
</syntaxhighlight>
We're able to use explicit typing to ensure that we're evaluating the expression as the desired type as in the example above. However, in most cases, Swift allows us to be more brief, and rely on '''type inference'''.  Type inference will rely on the literal value(s) or named value(s) to determine the type.  Let's look at a few examples:
<syntaxhighlight lang="swift">
let maximumClassCount = 8
// maximumClassCount will be of type Int
 
let maximumGPA = 5.0
// maximumGPA will be of type Double
</syntaxhighlight>
In addition to decimal, literal integer expressions Swift will also infer the Int type from binary, octal, and hexadecimal:
<syntaxhighlight lang="swift">
let n = 0b101 // An integer formed from a binary, literal constant
let m = 0o17  // An integer formed from an octal, literal constant
let p = 0x2F  // An integer formed from a hexadecimal, literal constant
</syntaxhighlight>
{{Caution|
Regardless of the base used in an integer expression, the ultimate value is simply an integer.}}
=== Floating Points ===
Floating point numbers may be specified in decimal or in hexadecimal.  Decimal numbers may have an optional exponent (indicated by '''e''' or '''E'''), which means that the base number is multiplied by <math>10^n</math>.
<syntaxhighlight lang="swift">
let f = 1.23e5 // f is a Double of value 123,000
</syntaxhighlight>
Hexadecimal numbers may also have an optional exponent (indicated by '''p''' or '''P'''), which means that the base number is multiplied by <math>2^n</math>.
<syntaxhighlight lang="swift">
let g = 0xFp3 // g is a Double of value 120
</syntaxhighlight>
Note that for ''literal constants'', Swift will interpret the expression as a Double if any of the component expressions evaluate to a Double.  ⚠ This does not apply to named constants.
=== Readability ===
Both integers and floating point numbers may have leading zeroes and embedded underscores for easier reading (by humans).
<syntaxhighlight lang="swift">
let oneBillion = 1_000_000_000
let tenBillion = 010_000_000_000
</syntaxhighlight>
=== Strings ===
A series of characters embedded within quotes will be inferred to be of type String:
<syntaxhighlight lang="swift">
let name = "Captain Picard"
</syntaxhighlight>
 
{{ComingSoon|
String length
}}
 
== Operators ==
In programming, '''operators''' provide us with the ability to write many expressions in a manner generally familiar to us from algebra. ''Operators'' can be grouped by '''arity''', that is, the number of
'''operands''' on which the operator will function. For example, the expression 4+5 makes use of a binary operator (addition) which takes two operands, in this case a 4 and a 5. (An arity of one is often called '''unary''' while an arity of two is often called '''binary'''.)
 
Some common operators are listed in the table below:
 
{| class="wikitable" style="text-align: center;"
! Name
! Symbol (Swift)
! Arity
! Type
|-
| Assignment || = || 2 || General
|-
| Unary Plus (Positive) || + || 1 || Arithmetic
|-
| Unary Minus (Negative) || - || 1 || Arithmetic
|-
| Addition || + || 2 || Arithmetic
|-
| Subtraction || - || 2 || Arithmetic
|-
| Multiplication || * || 2 || Arithmetic
|-
| Division || / || 2 || Arithmetic
|-
| Remainder || % || 2 || Arithmetic
|-
| Logical NOT || ! || 1 || Boolean
|-
| Logical AND || && || 2 || Boolean
|-
| Logical OR
<td> {{Bar}}{{Bar}} </td>
| 2
| Boolean
|-
| Equal to || == || 2 || Comparison
|-
| Not equal to || != || 2 || Comparison
|-
| Greater than || > || 2 || Comparison
|-
| Greater than or equal to || >= || 2 || Comparison
|-
| Less than || < || 2 || Comparison
|-
| Less than or equal to || <= || 2 || Comparison
|-
| Concatenation || + || 2 || String
|}
 
 
Some languages also support '''compound assignment''' operators, that is, they perform an operation on an L-Value and then store the result in the same L-Value. For example, the statements:
<pre>
var x = 9
x += 2
</pre>
assign the integer value of 9 to "x", and then increment "x" by 2, resulting in a new value for "x" of 11. This is exactly equivalent to:
<pre>
var x = 9
x=x+2
</pre>
 
== Expressions with Operators ==
We can use one or more operators with appropriate operands to form more complex expressions and assign the resultant value to a constant or variable:
<syntaxhighlight lang="swift">
let areaOfRectangle = 4.0 * 5.2
let radius = 2.7
let areaOfCircle = Double.pi * radius * radius
</syntaxhighlight>
The '''concatenation''' operator can be used to form more complex strings from simpler strings:
<syntaxhighlight lang="swift">
let firstName = "William"
let lastName = "Riker"
let fullName = firstName + " " + lastName
</syntaxhighlight>
 
 
{{ComingSoon|
Additional examples of expressions using operators}}
 
== Key Concepts ==
{{KeyConcepts|
* An '''expression''' is a finite series of symbols that is well-formed according to agreed upon rules
* A valid expression will yield a value of a specific type according to the rules of the language
* All expressions, when evaluated, yield a particular type
* On 32-bit platforms, '''Int''' will be equivalent to '''Int32'''
* On 64-bit platforms, '''Int''' will be equivalent to '''Int64'''
* Swift is a '''type-safe language''', all expressions will always have a specific type
** Type-safety enables the compiler to warn us when we make a mistake, such as by using an Int when we intended a Double
** We're able to use explicit typing to ensure that we're evaluating the expression as the desired type
* In most cases, Swift allows us to be more brief, and rely on '''type inference'''
** Type inference will rely on the literal value(s) or named value(s) to determine the type
* Integers may be specified in decimal, binary, octal, or hexadecimal
* Floating point numbers may be specified in decimal or hexadecimal
** Exponents may be specified by using '''e''' for decimal numbers and '''p''' for hexadecimal numbers
* Both integers and floating point numbers may have leading zeroes and embedded underscores
* A series of characters embedded within quotes will be inferred to be of type '''String'''
** The concatenation operator can be used to form more complex strings from simpler strings
* We can use one or more operators with appropriate operands to form more complex expressions
}}
== Exercises ==
{{W1037-Exercises}}
 
== References ==
* [https://en.wikipedia.org/wiki/Expression_(mathematics) Expressions] (Wikipedia.org)
* [https://docs.swift.org/swift-book/ReferenceManual/Expressions.html Expressions] (Swift.org)

Latest revision as of 23:13, 8 February 2024

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
HintIcon.png
Moved to Moodle logo.svg
CS-151,Unit III,Chapters 6-7