forked from swcarpentry/r-novice-inflammation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-supp-call-stack.html
106 lines (105 loc) · 9.89 KB
/
02-supp-call-stack.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<title>Software Carpentry: Programming with R</title>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
<link rel="stylesheet" type="text/css" href="css/swc.css" />
<link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
<meta charset="UTF-8" />
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body class="lesson">
<div class="container card">
<div class="banner">
<a href="http://software-carpentry.org" title="Software Carpentry">
<img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
</a>
</div>
<article>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<a href="index.html"><h1 class="title">Programming with R</h1></a>
<h2 class="subtitle">The call stack</h2>
<h3 id="the-call-stack">The Call Stack</h3>
<p>Let’s take a closer look at what happens when we call <code>fahr_to_celsius(32)</code>. 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:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">original <-<span class="st"> </span><span class="dv">32</span>
final <-<span class="st"> </span><span class="kw">fahr_to_celsius</span>(original)</code></pre></div>
<p>The diagram below shows what memory looks like after the first line has been executed:</p>
<p><img src="fig/python-call-stack-01.svg" alt="Call Stack (Initial State)" /></p>
<p>When we call <code>fahr_to_celsius</code>, R <em>doesn’t</em> create the variable <code>temp</code> right away. Instead, it creates something called a <a href="reference.html#stack-frame">stack frame</a> to keep track of the variables defined by <code>fahr_to_kelvin</code>. Initially, this stack frame only holds the value of <code>temp</code>:</p>
<p><img src="fig/python-call-stack-02.svg" alt="Call Stack Immediately After First Function Call" /></p>
<p>When we call <code>fahr_to_kelvin</code> inside <code>fahr_to_celsius</code>, R creates another stack frame to hold <code>fahr_to_kelvin</code>’s variables:</p>
<p><img src="fig/python-call-stack-03.svg" alt="Call Stack During First Nested Function Call" /></p>
<p>It does this because there are now two variables in play called <code>temp</code>: the argument to <code>fahr_to_celsius</code>, and the argument to <code>fahr_to_kelvin</code>. 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.</p>
<p>When the call to <code>fahr_to_kelvin</code> returns a value, R throws away <code>fahr_to_kelvin</code>’s stack frame and creates a new variable in the stack frame for <code>fahr_to_celsius</code> to hold the temperature in Kelvin:</p>
<p><img src="fig/python-call-stack-04.svg" alt="Call Stack After Return From First Nested Function Call" /></p>
<p>It then calls <code>kelvin_to_celsius</code>, which means it creates a stack frame to hold that function’s variables:</p>
<p><img src="fig/python-call-stack-05.svg" alt="Call Stack During Call to Second Nested Function" /></p>
<p>Once again, R throws away that stack frame when <code>kelvin_to_celsius</code> is done and creates the variable <code>result</code> in the stack frame for <code>fahr_to_celsius</code>:</p>
<p><img src="fig/python-call-stack-06.svg" alt="Call Stack After Second Nested Function Returns" /></p>
<p>Finally, when <code>fahr_to_celsius</code> is done, R throws away <em>its</em> stack frame and puts its result in a new variable called <code>final</code> that lives in the stack frame we started with:</p>
<p><img src="fig/python-call-stack-07.svg" alt="Call Stack After All Functions Have Finished" /></p>
<p>This final stack frame is always there; it holds the variables we defined outside the functions in our code. What it <em>doesn’t</em> hold is the variables that were in the various stack frames. If we try to get the value of <code>temp</code> after our functions have finished running, R tells us that there’s no such thing:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">temp</code></pre></div>
<pre><code>## Error in eval(expr, envir, enclos): object 'temp' not found</code></pre>
<aside class="callout panel panel-info">
<div class="panel-heading">
<h2 id="tip"><span class="glyphicon glyphicon-pushpin"></span>Tip</h2>
</div>
<div class="panel-body">
<p>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 <a href="http://cran.r-project.org/doc/manuals/r-release/R-lang.html#Environment-objects">R Language Manual</a> or this <a href="http://adv-r.had.co.nz/Environments.html">chapter</a> from <a href="http://adv-r.had.co.nz/">Advanced R Programming</a> by Hadley Wickham. For context, R uses the terminology “environments” instead of frames.</p>
</div>
</aside>
<p>Why go to all this trouble? Well, here’s a function called <code>span</code> that calculates the difference between the minimum and maximum values in an array:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">span <-<span class="st"> </span>function(a) {
diff <-<span class="st"> </span><span class="kw">max</span>(a) -<span class="st"> </span><span class="kw">min</span>(a)
<span class="kw">return</span>(diff)
}
dat <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="dt">file =</span> <span class="st">"data/inflammation-01.csv"</span>, <span class="dt">header =</span> <span class="ot">FALSE</span>)
<span class="co"># span of inflammation data</span>
<span class="kw">span</span>(dat)</code></pre></div>
<pre><code>## [1] 20</code></pre>
<p>Notice <code>span</code> assigns a value to variable called <code>diff</code>. We might very well use a variable with the same name (<code>diff</code>) to hold the inflammation data:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">diff <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="dt">file =</span> <span class="st">"data/inflammation-01.csv"</span>, <span class="dt">header =</span> <span class="ot">FALSE</span>)
<span class="co"># span of inflammation data</span>
<span class="kw">span</span>(diff)</code></pre></div>
<pre><code>## [1] 20</code></pre>
<p>We don’t expect the variable <code>diff</code> to have the value 20 after this function call, so the name <code>diff</code> cannot refer to the same variable defined inside <code>span</code> 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 <code>diff</code> 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.</p>
<p>The big idea here is <a href="reference.html#encapsulation">encapsulation</a>, 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.</p>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="challenge---following-the-call-stack"><span class="glyphicon glyphicon-pencil"></span>Challenge - Following the call stack</h2>
</div>
<div class="panel-body">
<ul>
<li>We previously wrote functions called <code>fence</code> and <code>outside</code>. Draw a diagram showing how the call stack changes when we run the following:</li>
</ul>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">inner_vec <-<span class="st"> "carbon"</span>
outer_vec <-<span class="st"> "+"</span>
result <-<span class="st"> </span><span class="kw">outside</span>(<span class="kw">fence</span>(inner_vec, outer_vec))</code></pre></div>
</div>
</section>
</div>
</div>
</article>
<div class="footer">
<a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
<a class="label swc-blue-bg" href="https://github.com/swcarpentry/r-novice-inflammation">Source</a>
<a class="label swc-blue-bg" href="mailto:[email protected]">Contact</a>
<a class="label swc-blue-bg" href="LICENSE.html">License</a>
</div>
</div>
<!-- Javascript placed at the end of the document so the pages load faster -->
<script src="http://software-carpentry.org/v5/js/jquery-1.9.1.min.js"></script>
<script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
<script src='https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script>
</body>
</html>