Difference between revisions of "W1205 Function Introduction"

From Coder Merlin
m (Editorial review and minor corrections)
 
(6 intermediate revisions by one other user not shown)
Line 1: Line 1:
[[File:Tektronix FG 504 Function generator with DC 503 Universal Counter.jpg|thumb|right|link=|Tektronix FG 504 Function generator with DC 503 Universal Counter]]
[[File:Tektronix FG 504 Function generator with DC 503 Universal Counter.jpg|thumb|right|link=|Tektronix FG 504 Function Generator with DC 503 Universal Counter]]
== Prerequisites ==
== Prerequisites ==
* [[W1102 Types]]
* [[W1102 Types]]
Line 5: Line 5:
Functions enable us to package a sequence of statements that we could easily reuse whenever desired.  Functions can be used to break up a larger program into smaller, more easily understood units.   
Functions enable us to package a sequence of statements that we could easily reuse whenever desired.  Functions can be used to break up a larger program into smaller, more easily understood units.   


The code contained within a function is known as the '''body''' of the function.  Some functions, similar to the way we use functions in algebra, expect one or more values to be provided by the calling program when it '''invokes''' the function.  The function declares placeholders, called '''parameters''' for each value required.  The ''type'' of value must also be specified.  When the function is later invoked, the calling program specifies the actual '''arguments''' which must match the declared parameters.   
The code contained within a function is known as the '''body''' of the function.  Some functions, similar to the way we use functions in algebra, expect one or more values to be provided by the calling program when it '''invokes''' the function.  The function declares placeholders, called '''parameters''' for each value required.  The ''type'' of value must also be specified.  When the function is later invoked, the calling program specifies the actual '''arguments''' that must match the declared parameters.   


Some functions may also '''return''' a value back to the caller (again, similar to the way we think of functions in algebra).  In many cases functions will indeed behave as algebraic functions, where the returned value is dependent entirely on the argument(s).
Some functions may also '''return''' a value back to the caller (again, similar to the way we think of functions in algebra).  In many cases functions will indeed behave as algebraic functions, where the returned value is dependent entirely on the argument or arguments.


== Function Invocation ==
== Function Invocation ==
Activating (or calling) a function is formally termed '''function invocation'''.  An example of invoking an algebraic-like function is:
Activating (or calling) a function is formally termed '''function invocation'''.  An example of invoking an algebraic-like function is:
<syntaxhighlight lang="swift">
{{CodeExplorer
let xCoordinate = cos(Double.pi * 2)
|exerciseID=1
</syntaxhighlight>
|height=120
|language=swift
|initialCode=
import Foundation // Imports a library of common functions, including trigonometric functions
let radians = Double.pi / 4.0
let x = cos(radians)
let y = sin(radians)
print("(x, y) = (\(x), \(y))")
}}
In this case, the name of the function is "cos" taking a single argument of type Double and returning a Double.
In this case, the name of the function is "cos" taking a single argument of type Double and returning a Double.


== Side Effects ==
== Side Effects ==
In the above case, the function has no '''side-effects''', that is, it does not in anyway modify any data structures elsewhere, it simply returns a value. In other cases, however, it may be desirable to perform some side effect. For example, functions are available to open a file for writing or to retrieve a web page specified by a URL parameter.  
In the above case, the function has no '''side-effects''', that is, it does not in any way modify any data structures elsewhere. It simply returns a value. In other cases, however, it might be desirable to perform some side effect. For example, functions are available to open a file for writing or to retrieve a web page specified by a URL parameter.  
== Anatomy of a Swift Function Declaration ==
== Anatomy of a Swift Function Declaration ==
<syntaxhighlight lang="swift">
{{CodeExplorer
func sayHello(toPersonName:String) {
|exerciseID=2
     print("Hello, \(toPersonName)")
|height=120
|language=swift
|initialCode=
func sayHello(to personName: String) {
     print("Hello, \(personName)")
}
}
</syntaxhighlight>
// Nothing happens yet, because we haven't yet invoked the function
}}
In the above example:  
In the above example:  
* '''func''' is a keyword indicating that we're about to define a function
* {{SwiftKeyword|func}} is a keyword indicating that we're about to define a function.
* ''sayHello'' is the '''name''' of the function
* ''sayHello'' is the '''name''' of the function.
* ''toPersonName'' serves as both the '''argument label''' and '''parameter name'''.  By default, these share the same name.
* ''to personName'' provides the {{GlossaryReference|Argument|argument label}} followed by the {{GlossaryReference|Parameter|parameter name}}.
** The ''argument label'' is used when invoking the function
** The {{GlossaryReference|Argument|argument label}} is used when invoking the function.
** The ''parameter name'' is used to refer to the parameter ''within'' the function
** The {{GlossaryReference|Parameter|parameter name}} is used to refer to the parameter ''within'' the scope of the function.
* The '''body''' of the function contains the code executed when the function is invoked. In the above case, this is the print statement.
* The '''body''' of the function contains the code executed when the function is invoked. In the above case, this is the print statement.


A function may optionally return a value to the '''caller''' (the code which invoked the function). In the below example, the function specifies the '''return type''' as ''String'' and uses the keyword '''return''' at the end of the function to return the value.
A function may optionally return a value to the '''caller''' (the code that invoked the function). In the below example, the function specifies the '''return type''' as ''String'' and uses the keyword '''return''' at the end of the function to return the value.
<syntaxhighlight lang="swift">
<syntaxhighlight lang="swift">
func fullName(firstName:String, lastName:String) -> String {
func fullName(firstName:String, lastName:String) -> String {
Line 39: Line 52:
</syntaxhighlight>
</syntaxhighlight>


If a function does indicate a return type then it must return a value at each exit point from the function.
If a function does indicate a return type, it must return a value at each exit point from the function.


== Anatomy of a Swift Function Invocation ==
== Anatomy of a Swift Function Invocation ==
A function is '''invoked''' by simply using the function name followed by a list of '''arguments''' which must match the function's declared '''parameter list'''.  Each argument consists of an '''argument label''', a colon, and the associated value ('''argument'''). If a value is returned, we simply ''assign'' this to a constant or a variable.
A function is '''invoked''' by simply using the function name followed by a list of '''arguments''' that must match the function's declared '''parameter list'''.  Each argument consists of an '''argument label''', a colon, and the associated value ('''argument'''). If a value is returned, we simply ''assign'' this to a constant or a variable.


<syntaxhighlight lang="swift">
<syntaxhighlight lang="swift">
Line 51: Line 64:


== Advantages of Functions ==
== Advantages of Functions ==
Functions help us to break apart ('''decompose''') complex tasks into simpler steps. They also enable us to '''reduce the duplication''' of code because rather than copying the same code to multiple places in our program we can simply invoke the same function, perhaps with different arguments. We can also leverage this ability to divide larger programming tasks among multiple software development engineers by defining the requirements of each function and then allowing different engineers to implement different functions. Finally, functions '''hide implementation details''' so the user of a function can focus on the task at hand rather than worry about how the function is written. (For example, when using cos() function there’s no need to worry about how the function works, only that it does its job of returning the cosine of the given argument.)
Functions help us to break apart ('''decompose''') complex tasks into simpler steps. They also enable us to '''reduce the duplication''' of code because rather than copying the same code to multiple places in our program, we can simply invoke the same function, perhaps with different arguments. We can also leverage this ability to divide larger programming tasks among multiple software development engineers by defining the requirements of each function and then allowing different engineers to implement different functions. Finally, functions '''hide implementation details''' so the user of a function can focus on the task at hand rather than worry about how the function is written. For example, when using cos() function there's no need to worry about how the function works, only that it does its job of returning the cosine of the given argument.
== Return Means Now ==
== Return Means Now ==
Whenever the '''return''' statement is encountered the function immediately exits and returns to the caller. Subsequent code is not executed.
Whenever the '''return''' statement is encountered, the function immediately exits and returns to the caller. Subsequent code is not executed.


== Key Concepts ==
== Key Concepts ==
{{KeyConcepts|
{{KeyConcepts|
* Functions enable us to package a sequence of statements that we could easily reuse whenever desired. Advantages of functions include:
* Functions enable us to package a sequence of statements that we could easily reuse whenever desired. Advantages of functions are as follows:
** '''Decomposing''' complex tasks into simpler steps
** '''Decomposing''' complex tasks into simpler steps
** '''Reducing''' the duplication of code
** '''Reducing''' the duplication of code
** '''Hiding''' implementation details
** '''Hiding''' implementation details
* '''func''' is a keyword indicating that we're about to define a function
* '''func''' is a keyword indicating that we're about to define a function.
* The code contained within a function is known as the '''body''' of the function
* The code contained in a function is known as the '''body''' of the function.
* Some functions require parameters
* Some functions require parameters.
** The function declares placeholders, called '''parameters''' for each value required, and the type of value must also be specified
** The function declares placeholders, called '''parameters''' for each value required, and the type of value must also be specified.
** Each argument generally has an '''argument label''' used when invoking the function, and a '''parameter name''' used to refer to the parameter within the function.  Generally, these share the same name.
** Each argument generally has an '''argument label''' used when invoking the function, and a '''parameter name''' used to refer to the parameter within the function.  Generally, these share the same name.
** Some functions may '''return''' a value back to the caller  
** Some functions can '''return''' a value back to the caller.
* A function may or may not have '''side-effects'''.  A ''side-effect'' means that some data structure ''external'' to the function is altered through function invocation.
* A function may or may not have '''side-effects'''.  A ''side-effect'' means that some data structure ''external'' to the function is altered through function invocation.
* Activating (or calling) a function is formally termed '''function invocation'''
* Activating (or calling) a function is formally termed '''function invocation'''.
* When invoking a function with a parameter list, we must specify a corresponding '''argument''' for each required parameter
* When invoking a function with a parameter list, we must specify a corresponding '''argument''' for each required parameter.
** We use the '''argument label''' to prefix each argument
** We use the '''argument label''' to prefix each argument.
* Whenever the '''return''' statement is encountered the function immediately exits and returns to the caller.   
* Whenever the '''return''' statement is encountered the function immediately exits and returns to the caller.   
** Subsequent code is not executed.
** Subsequent code is not executed.

Latest revision as of 16:44, 7 February 2023

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Tektronix FG 504 Function Generator with DC 503 Universal Counter

Prerequisites[edit]

Introduction[edit]

Functions enable us to package a sequence of statements that we could easily reuse whenever desired. Functions can be used to break up a larger program into smaller, more easily understood units.

The code contained within a function is known as the body of the function. Some functions, similar to the way we use functions in algebra, expect one or more values to be provided by the calling program when it invokes the function. The function declares placeholders, called parameters for each value required. The type of value must also be specified. When the function is later invoked, the calling program specifies the actual arguments that must match the declared parameters.

Some functions may also return a value back to the caller (again, similar to the way we think of functions in algebra). In many cases functions will indeed behave as algebraic functions, where the returned value is dependent entirely on the argument or arguments.

Function Invocation[edit]

Activating (or calling) a function is formally termed function invocation. An example of invoking an algebraic-like function is:

CoderMerlin™ Code Explorer: W0000 (1) 🟢

In this case, the name of the function is "cos" taking a single argument of type Double and returning a Double.

Side Effects[edit]

In the above case, the function has no side-effects, that is, it does not in any way modify any data structures elsewhere. It simply returns a value. In other cases, however, it might be desirable to perform some side effect. For example, functions are available to open a file for writing or to retrieve a web page specified by a URL parameter.

Anatomy of a Swift Function Declaration[edit]

CoderMerlin™ Code Explorer: W0000 (2) 🟢

In the above example:

  • func is a keyword indicating that we're about to define a function.
  • sayHello is the name of the function.
  • to personName provides the argument label followed by the parameter name.
    • The argument label is used when invoking the function.
    • The parameter name is used to refer to the parameter within the scope of the function.
  • The body of the function contains the code executed when the function is invoked. In the above case, this is the print statement.

A function may optionally return a value to the caller (the code that invoked the function). In the below example, the function specifies the return type as String and uses the keyword return at the end of the function to return the value.

func fullName(firstName:String, lastName:String) -> String {
    return "\(lastName), \(firstName)"
}

If a function does indicate a return type, it must return a value at each exit point from the function.

Anatomy of a Swift Function Invocation[edit]

A function is invoked by simply using the function name followed by a list of arguments that must match the function's declared parameter list. Each argument consists of an argument label, a colon, and the associated value (argument). If a value is returned, we simply assign this to a constant or a variable.

let studentName = fullName(firstName:"John", lastName:"Williams")

In the above example, fullName is the function name, firstName:"John", lastName:"Williams" is the argument list, where firstName and lastName are argument labels and John and Williams are the corresponding arguments.

Advantages of Functions[edit]

Functions help us to break apart (decompose) complex tasks into simpler steps. They also enable us to reduce the duplication of code because rather than copying the same code to multiple places in our program, we can simply invoke the same function, perhaps with different arguments. We can also leverage this ability to divide larger programming tasks among multiple software development engineers by defining the requirements of each function and then allowing different engineers to implement different functions. Finally, functions hide implementation details so the user of a function can focus on the task at hand rather than worry about how the function is written. For example, when using cos() function there's no need to worry about how the function works, only that it does its job of returning the cosine of the given argument.

Return Means Now[edit]

Whenever the return statement is encountered, the function immediately exits and returns to the caller. Subsequent code is not executed.

Key Concepts[edit]

Key ConceptsKeyConceptsIcon.png
  • Functions enable us to package a sequence of statements that we could easily reuse whenever desired. Advantages of functions are as follows:
    • Decomposing complex tasks into simpler steps
    • Reducing the duplication of code
    • Hiding implementation details
  • func is a keyword indicating that we're about to define a function.
  • The code contained in a function is known as the body of the function.
  • Some functions require parameters.
    • The function declares placeholders, called parameters for each value required, and the type of value must also be specified.
    • Each argument generally has an argument label used when invoking the function, and a parameter name used to refer to the parameter within the function. Generally, these share the same name.
    • Some functions can return a value back to the caller.
  • A function may or may not have side-effects. A side-effect means that some data structure external to the function is altered through function invocation.
  • Activating (or calling) a function is formally termed function invocation.
  • When invoking a function with a parameter list, we must specify a corresponding argument for each required parameter.
    • We use the argument label to prefix each argument.
  • Whenever the return statement is encountered the function immediately exits and returns to the caller.
    • Subsequent code is not executed.

Exercises[edit]

ExercisesExercisesIcon.png
  •  M1205-10  Complete  Merlin Mission Manager  Mission M1205-10.

References[edit]