---
tags: Labs-F21, 2021
title: Snap Guide!
---
# Snap: What's going on here?

Welcome to [Snap](https://snap.berkeley.edu/snap/snap.html)! Snap is a tool built to visualize how programs run. It's somewhat similar to Scratch, if you've used that.
We're going to be using Snap in 111 to visualize recursive function calls.
Let's take a look at the following pen-and-paper visualization for the function `sum`, and convert it to a Snap diagram:
Here's the Pyret code for sum:
```
fun sum(lon :: List<Number>) -> Number:
cases (List) lon:
| empty => 0
| link(fst, rst) fst + sum(rst) # POINT 2
end
end
sum([list: 1, 4, -1]) # POINT 1
```
And here's a visualization of what happens when we run `sum` with input `[list: 1, -4, 0]`:

Make sure you understand what's going on in this diagram before transitioning to Snap.
### Makes sense, onto Snap
Let's convert the example above to Snap.
We'll start by writing the recursive visualization **only** through Call 1. Below is the Snap diagram.

Let's take a deeper look at the diagram. **Call Records** are containers that display all of the data relevant to a function call. Notice that in this diagram we have two Call Records. In our code, these refer to the first time we invoke sum and the first time we invoke sum recursively.
Notice that the first Call Record, which represents the first time `sum` is invoked, only has two fields filled out: **Call** and **Local Context**. The Call field displays our function call. The Local Context field contains information on where the output of the function call will go. For example, for the expression `1 + string-length('cat')`, `string-length('cat')` is the Call and `1 + []` is the Local Context.
Our second Call Record, which represents the first time `sum` is invoked recursively, also has the fields **Parameters** and **Local Variables** filled out. These fields contain **Bindings**, which for our purposes are Pyret names. For example, the expression `x = 4` represents the Binding `x` to `4`. The Parameters field contains bindings for function inputs. The Local Variables field contains bindings for any names defined within the body of the function. In our `sum` example, `lon` gets placed in Parameters because it is passed as an input to the function. Similarly, `fst` and `rst` are Local Variables because we define them within the function.
If we run through the full `sum` example, we get the following Snap diagram:

Notice that we end the recursive chain with a Binding, not a function call, when we call `sum(empty)`. This is because when we get to the base case (when the list is empty), we make no further function calls.
Snap!