Skip to content

Commit

Permalink
eval false for PR #158
Browse files Browse the repository at this point in the history
  • Loading branch information
chendaniely committed Jun 14, 2016
1 parent 4f7f5fd commit 23ba94b
Show file tree
Hide file tree
Showing 3 changed files with 135 additions and 136 deletions.
137 changes: 3 additions & 134 deletions 02-func-R.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ minutes: 30
> * Define a function that takes arguments.
> * Return a value from a function.
> * Test a function.
> * Explain what a call stack is, and trace changes to the call stack as functions are called.
> * Set default values for function arguments.
> * Explain why we should divide programs into small, single-purpose functions.
Expand Down Expand Up @@ -165,139 +164,10 @@ Real-life functions will usually be larger than the ones shown here--typically h
>
> ~~~
### The Call Stack
Let's take a closer look at what happens when we call `fahr_to_celsius(32)`. To make things clearer, we'll start by putting the initial value 32 in a variable and store the final result in one as well:
~~~{.r}
original <- 32
final <- fahr_to_celsius(original)
~~~
The diagram below shows what memory looks like after the first line has been executed:

<img src="fig/python-call-stack-01.svg" alt="Call Stack (Initial State)" />

When we call `fahr_to_celsius`, R *doesn't* create the variable `temp` right away.
Instead, it creates something called a [stack frame](reference.html#stack-frame) to keep track of the variables defined by `fahr_to_kelvin`.
Initially, this stack frame only holds the value of `temp`:

<img src="fig/python-call-stack-02.svg" alt="Call Stack Immediately After First Function Call" />

When we call `fahr_to_kelvin` inside `fahr_to_celsius`, R creates another stack frame to hold `fahr_to_kelvin`'s variables:

<img src="fig/python-call-stack-03.svg" alt="Call Stack During First Nested Function Call" />

It does this because there are now two variables in play called `temp`: the argument to `fahr_to_celsius`, and the argument to `fahr_to_kelvin`.
Having two variables with the same name in the same part of the program would be ambiguous, so R (and every other modern programming language) creates a new stack frame for each function call to keep that function's variables separate from those defined by other functions.

When the call to `fahr_to_kelvin` returns a value, R throws away `fahr_to_kelvin`'s stack frame and creates a new variable in the stack frame for `fahr_to_celsius` to hold the temperature in Kelvin:

<img src="fig/python-call-stack-04.svg" alt="Call Stack After Return From First Nested Function Call" />

It then calls `kelvin_to_celsius`, which means it creates a stack frame to hold that function's variables:

<img src="fig/python-call-stack-05.svg" alt="Call Stack During Call to Second Nested Function" />

Once again, R throws away that stack frame when `kelvin_to_celsius` is done
and creates the variable `result` in the stack frame for `fahr_to_celsius`:

<img src="fig/python-call-stack-06.svg" alt="Call Stack After Second Nested Function Returns" />

Finally, when `fahr_to_celsius` is done, R throws away *its* stack frame and puts its result in a new variable called `final` that lives in the stack frame we started with:

<img src="fig/python-call-stack-07.svg" alt="Call Stack After All Functions Have Finished" />

This final stack frame is always there;
it holds the variables we defined outside the functions in our code.
What it *doesn't* hold is the variables that were in the various stack frames.
If we try to get the value of `temp` after our functions have finished running, R tells us that there's no such thing:


~~~{.r}
temp
~~~



~~~{.error}
Error in eval(expr, envir, enclos): object 'temp' not found
~~~

> ## Tip {.callout}
> ## The call stack {.callout}
>
> The explanation of the stack frame above was very general and the basic
> concept will help you understand most languages you try to program with.
> However, R has some unique aspects that can be exploited when performing
> more complicated operations. We will not be writing anything that requires
> knowledge of these more advanced concepts. In the future when you are
> comfortable writing functions in R, you can learn more by reading the
> [R Language Manual][man] or this [chapter][] from
> [Advanced R Programming][adv-r] by Hadley Wickham. For context, R uses the
> terminology "environments" instead of frames.
> For a deeper understanding of how functions work, you'll need to learn how they create their own environments and call other functions. Function calls are managed via the call stack. For more details on the call stack, have a look at the [supplementary material](02-supp-call-stack.html).
[man]: http://cran.r-project.org/doc/manuals/r-release/R-lang.html#Environment-objects
[chapter]: http://adv-r.had.co.nz/Environments.html
[adv-r]: http://adv-r.had.co.nz/

Why go to all this trouble? Well, here's a function called `span` that calculates the difference between the minimum and maximum values in an array:


~~~{.r}
span <- function(a) {
diff <- max(a) - min(a)
return(diff)
}
dat <- read.csv(file = "data/inflammation-01.csv", header = FALSE)
# span of inflammation data
span(dat)
~~~



~~~{.output}
[1] 20
~~~

Notice `span` assigns a value to variable called `diff`. We might very well use a variable with the same name (`diff`) to hold the inflammation data:


~~~{.r}
diff <- read.csv(file = "data/inflammation-01.csv", header = FALSE)
# span of inflammation data
span(diff)
~~~



~~~{.output}
[1] 20
~~~

We don't expect the variable `diff` to have the value 20 after this function call, so the name `diff` cannot refer to the same variable defined inside `span` as it does in as it does in the main body of our program (which R refers to as the global environment).
And yes, we could probably choose a different name than `diff` for our variable in this case, but we don't want to have to read every line of code of the R functions we call to see what variable names they use, just in case they change the values of our variables.

The big idea here is [encapsulation](reference.html#encapsulation), and it's the key to writing correct, comprehensible programs.
A function's job is to turn several operations into one so that we can think about a single function call instead of a dozen or a hundred statements each time we want to do something.
That only works if functions don't interfere with each other; if they do, we have to pay attention to the details once again, which quickly overloads our short-term memory.

> ## Challenge - Following the call stack {.challenge}
>
> + We previously wrote functions called `fence` and `outside`.
> Draw a diagram showing how the call stack changes when we run the
> following:
>
> ~~~{.r}
> inner_vec <- "carbon"
> outer_vec <- "+"
> result <- outside(fence(inner_vec, outer_vec))
> ~~~
### Testing and Documenting
Expand Down Expand Up @@ -775,7 +645,6 @@ It fails because `FALSE` is assigned to `file` and the filename is assigned to t
>
> * Define a function using `name <- function(...args...) {...body...}`.
> * Call a function using `name(...values...)`.
> * Each time a function is called, a new stack frame is created on the [call stack](reference.html#call-stack) to hold its arguments and local variables.
> * R looks for variables in the current stack frame before looking for them at the top level.
> * Use `help(thing)` to view help for something.
> * Put comments at the beginning of functions to provide help for that function.
Expand All @@ -787,7 +656,7 @@ It fails because `FALSE` is assigned to `file` and the filename is assigned to t
>
> We now have a function called analyze to visualize a single data set.
> We could use it to explore all 12 of our current data sets like this:
>
>
>
> ~~~{.r}
> analyze("data/inflammation-01.csv")
Expand Down
4 changes: 2 additions & 2 deletions 02-supp-call-stack.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ minutes: 15

Let's take a closer look at what happens when we call `fahr_to_celsius(32)`. To make things clearer, we'll start by putting the initial value 32 in a variable and store the final result in one as well:

```{r}
```{r, eval = FALSE}
original <- 32
final <- fahr_to_celsius(original)
```
Expand Down Expand Up @@ -106,7 +106,7 @@ That only works if functions don't interfere with each other; if they do, we hav
> + We previously wrote functions called `fence` and `outside`.
> Draw a diagram showing how the call stack changes when we run the
> following:
> ```{r, results="hide"}
> ```{r, results="hide", eval = FALSE}
> inner_vec <- "carbon"
> outer_vec <- "+"
> result <- outside(fence(inner_vec, outer_vec))
Expand Down
130 changes: 130 additions & 0 deletions 02-supp-call-stack.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
---
layout: page
title: Programming with R
subtitle: The call stack
minutes: 15
---

### The Call Stack

Let's take a closer look at what happens when we call `fahr_to_celsius(32)`. To make things clearer, we'll start by putting the initial value 32 in a variable and store the final result in one as well:


```r
original <- 32
final <- fahr_to_celsius(original)
```

The diagram below shows what memory looks like after the first line has been executed:

<img src="fig/python-call-stack-01.svg" alt="Call Stack (Initial State)" />

When we call `fahr_to_celsius`, R *doesn't* create the variable `temp` right away.
Instead, it creates something called a [stack frame](reference.html#stack-frame) to keep track of the variables defined by `fahr_to_kelvin`.
Initially, this stack frame only holds the value of `temp`:

<img src="fig/python-call-stack-02.svg" alt="Call Stack Immediately After First Function Call" />

When we call `fahr_to_kelvin` inside `fahr_to_celsius`, R creates another stack frame to hold `fahr_to_kelvin`'s variables:

<img src="fig/python-call-stack-03.svg" alt="Call Stack During First Nested Function Call" />

It does this because there are now two variables in play called `temp`: the argument to `fahr_to_celsius`, and the argument to `fahr_to_kelvin`.
Having two variables with the same name in the same part of the program would be ambiguous, so R (and every other modern programming language) creates a new stack frame for each function call to keep that function's variables separate from those defined by other functions.

When the call to `fahr_to_kelvin` returns a value, R throws away `fahr_to_kelvin`'s stack frame and creates a new variable in the stack frame for `fahr_to_celsius` to hold the temperature in Kelvin:

<img src="fig/python-call-stack-04.svg" alt="Call Stack After Return From First Nested Function Call" />

It then calls `kelvin_to_celsius`, which means it creates a stack frame to hold that function's variables:

<img src="fig/python-call-stack-05.svg" alt="Call Stack During Call to Second Nested Function" />

Once again, R throws away that stack frame when `kelvin_to_celsius` is done
and creates the variable `result` in the stack frame for `fahr_to_celsius`:

<img src="fig/python-call-stack-06.svg" alt="Call Stack After Second Nested Function Returns" />

Finally, when `fahr_to_celsius` is done, R throws away *its* stack frame and puts its result in a new variable called `final` that lives in the stack frame we started with:

<img src="fig/python-call-stack-07.svg" alt="Call Stack After All Functions Have Finished" />

This final stack frame is always there;
it holds the variables we defined outside the functions in our code.
What it *doesn't* hold is the variables that were in the various stack frames.
If we try to get the value of `temp` after our functions have finished running, R tells us that there's no such thing:


```r
temp
```

```
## Error in eval(expr, envir, enclos): object 'temp' not found
```

> ## Tip {.callout}
>
> The explanation of the stack frame above was very general and the basic
> concept will help you understand most languages you try to program with.
> However, R has some unique aspects that can be exploited when performing
> more complicated operations. We will not be writing anything that requires
> knowledge of these more advanced concepts. In the future when you are
> comfortable writing functions in R, you can learn more by reading the
> [R Language Manual][man] or this [chapter][] from
> [Advanced R Programming][adv-r] by Hadley Wickham. For context, R uses the
> terminology "environments" instead of frames.
[man]: http://cran.r-project.org/doc/manuals/r-release/R-lang.html#Environment-objects
[chapter]: http://adv-r.had.co.nz/Environments.html
[adv-r]: http://adv-r.had.co.nz/

Why go to all this trouble? Well, here's a function called `span` that calculates the difference between the minimum and maximum values in an array:


```r
span <- function(a) {
diff <- max(a) - min(a)
return(diff)
}

dat <- read.csv(file = "data/inflammation-01.csv", header = FALSE)
# span of inflammation data
span(dat)
```

```
## [1] 20
```

Notice `span` assigns a value to variable called `diff`. We might very well use a variable with the same name (`diff`) to hold the inflammation data:


```r
diff <- read.csv(file = "data/inflammation-01.csv", header = FALSE)
# span of inflammation data
span(diff)
```

```
## [1] 20
```

We don't expect the variable `diff` to have the value 20 after this function call, so the name `diff` cannot refer to the same variable defined inside `span` as it does in as it does in the main body of our program (which R refers to as the global environment).
And yes, we could probably choose a different name than `diff` for our variable in this case, but we don't want to have to read every line of code of the R functions we call to see what variable names they use, just in case they change the values of our variables.

The big idea here is [encapsulation](reference.html#encapsulation), and it's the key to writing correct, comprehensible programs.
A function's job is to turn several operations into one so that we can think about a single function call instead of a dozen or a hundred statements each time we want to do something.
That only works if functions don't interfere with each other; if they do, we have to pay attention to the details once again, which quickly overloads our short-term memory.

> ## Challenge - Following the call stack {.challenge}
>
> + We previously wrote functions called `fence` and `outside`.
> Draw a diagram showing how the call stack changes when we run the
> following:
>
> ```r
> inner_vec <- "carbon"
> outer_vec <- "+"
> result <- outside(fence(inner_vec, outer_vec))
> ```

0 comments on commit 23ba94b

Please sign in to comment.