This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//--------- Sample 1 ------------- | |
/// Factorial | |
let rec fact n = | |
if n = 1 then 1 | |
else n*fact(n-1) | |
/// Tail optimized Factorial | |
let fact n = | |
let rec factImpl n acc = // acc = accumulator | |
if n = 1 then acc | |
else factImpl (n-1) (acc*n) | |
factImpl n 1 | |
//--------- Sample 2 ------------- | |
/// Fibonacci numbers | |
let rec fib n = | |
if n = 0 || n = 1 | |
then 1 | |
else fib (n-1) + fib (n-2) | |
/// Tail optimized Fibonacci numbers | |
let fib n = | |
let rec fibImpl n cont = // cont = continuation | |
if n = 0 || n = 1 | |
then cont(1) | |
else fibImpl (n-1) (fun res1 -> | |
fibImpl (n-2) (fun res2 -> | |
cont(res1+res2))) | |
fibImpl n (id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment