20-CS-4003-001 Organization of Programming Languages Fall 2017
Recursion

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures           Code

Example: Fibonacci numbers

   
fib::Int -> Integer
fib n = (1 : 1 : ys) !! (n-1)
   where ys = [ x + y
              | x <- 1 : ys
              | y <- 1 : 1 : ys]
 -  Find the nth Fibonacci number. The list comprehension has three parts! The last part (y <- 1 : 1 : ys) creates a list y of tokens beginning with two 1's followed by whatever ys becomes. The next to last part (x <- 1 : ys) creates a list x of tokens beginning with a single 1 followed by whatever ys becomes. The first part (x+y) adds the lists x and y. The following shows what ys turns out to be (it is initially [] because there is no <token>: in front of the list comprehension):
    y: 1 1 2 3 5 8 ...
    x: 1 2 3 5 8 ...
   ys: 2 3 5 8 ...
The red numbers indicate the list ys values in lists x and y. The !!(n-1) returns the nth number in the list [1,1]++ys.
 
fib::(Ord a, Num a)=>a->a->a->a
fib a b n = y
  where 
    y = if (n < 3) then a
        else fib (a+b) a (n-1)
		  
fibon n = fib 1 1 n
 -  An alternative recursive function to compute the nth Fibonacci number.