Docsity

Objectives and Problems - Programming Languages and Translators | CS 440, Study notes of Programming Languages

Toggle sidebar
bg1
CS 440 Recursion August 27, 2008
1 Objectives
Recursion is one of the most powerful ideas in Computer Science and in Mathematics. A proper understand-
ing of it is essential. All the lectures from here on out will really be about recursion.
•Understand how recursion is related to induction
•Know four patterns of recursion:
Iterating, Mapping, Folding, Accumulating
•Know how to determine the time complexity of a recursive operation
•Know how to turn a linear recursion into an exponential recursion
2 Problems
2.1 Activity 1
Write the factorial function.
2.2 Activity 2
Write the function inclist that returns an incremented version of the list given to it.
Mattox Beckman Page 1 Illinois Institute of Technology
pf2

Partial preview of the text

Download Objectives and Problems - Programming Languages and Translators | CS 440 and more Study notes Programming Languages in PDF only on Docsity!

CS 440 Recursion August 27, 2008

1 Objectives

Recursion is one of the most powerful ideas in Computer Science and in Mathematics. A proper understand- ing of it is essential. All the lectures from here on out will really be about recursion.

  • Understand how recursion is related to induction
  • Know four patterns of recursion: Iterating, Mapping, Folding, Accumulating
  • Know how to determine the time complexity of a recursive operation
  • Know how to turn a linear recursion into an exponential recursion

2 Problems

2.1 Activity 1

Write the factorial function.

2.2 Activity 2

Write the function inclist that returns an incremented version of the list given to it.

Mattox Beckman Page 1 Illinois Institute of Technology

CS 440 Recursion August 27, 2008

2.3 Activity 3

  1. Write a function that takes the sum of a list.
  2. Write a function that returns the running sum of a list.

2.4 Activity 4

Find the tail calls!

1 (define (calc n i) 2 (cond [(= n 2) i] 3 [(= (modulo n 2) 1) 4 (calc (+ 1 (* n 3)) (+ 1 i))] 5 [else (calc (/ n 2) (+ i 1))])) 6 7 (define (fib n) 8 (cond [(= n 0) 0] 9 [(= n 1) 1] 10 [else (+ (fib (- n 1)) (fib (- n 2)))]))

2.5 Activity 5

  1. Write an OCaml function that returns the maximum element of a list. Use forward recursion. (Assume the list always has at least 1 element.)
  2. Now write the same function, but use tail recursion.
  3. What is the running time of the following function?

1 (define (fib n) 2 (cond [(= n 0) 0] 3 [(= n 1) 1] 4 [else (+ (fib (- n 1)) (fib (- n 2)))]))

  1. Fix the above function to make it run in linear time. Hint: use two accumulators.

Mattox Beckman Page 2 Illinois Institute of Technology