Benutzer:MovGP0/F♯/Recursion

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


Recursive Functions

[Bearbeiten | Quelltext bearbeiten]
let rec fib = 
   if n <= 2 
   then 1
   else fib (n - 1) + fib (n - 2)

let rec sum list = 
   match list with 
   | head :: tail -> head + sum tail
   | [] -> 0

let rec len list = 
   match list with
   | head :: tail -> 1 + len tail
   | [] -> 0

let rec mymap f = function
   | [] -> []
   | x :: xs -> f x::mymap f xs
// clutters the stack
let rec factorial = 
   match n with
   | 0 | 1 -> 1
   | _ -> n * factorial (n-1)

// tail recursive version
let factorial n = 
   let rec tailRecursiveFactorial n acc = 
      match n with
      | 0 -> acc
      | _ -> tailRecursiveFactorial (n - 1) (acc * n)
   tailRecursiveFactorial n 1