rec05 - CS 3110 Recitation 5: Folding and tail recursion...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the 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 -> 0 | x::xs -> 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 -> "" | x::xs -> 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 -> acc | x::xs -> 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

Page1 / 3

rec05 - CS 3110 Recitation 5: Folding and tail recursion...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online