This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: CS 3110 Recitation 5: Folding and tail recursion Folding Suppose we want to write a function to sum a list of integers. By now you should be able to write the following code: let rec sum (l:int list):int = match l with -&gt; 0 | x::xs -&gt; x + (sum xs) Now suppose we want to concatenate a list of strings. We can write: let rec concat (l:string list):string = match l with -&gt; &quot;&quot; | x::xs -&gt; x ^ (concat xs) Notice that both functions look almost identical. With the exception of the different types and different operation (^ vs +), both functions are equivalent. In both cases, we walk down a list performing some operation with the data at each step. Since we love to reuse code in this class, is there some easier way to encode this? It turns out we can abstract all of the details of traversing a list. The idea is simple. As we walk across a list, we store an accumulator , a value that stores some data that is important to us. For example, if we want to walk across a list of integers and sum them, we could store the current sum in the accumulator. We start with the accumulator set to 0. As we come across each new element, we add the element to the accumulator. When we reach the end, we return the value stored in the accumulator. Let's try to rewrite the sum function to introduce the idea of an accumulator. let rec sum' (acc:int) (l:int list):int = match l with -&gt; acc | x::xs -&gt; sum' (acc+x) xs Of course, to get the sum, we must call sum' with 0 for the initial acc value. Similarly, we can rewrite concat with this concept of the accumulator....
View Full Document
This note was uploaded on 10/25/2009 for the course PHYS 2214 at Cornell.