Download code
From LiteratePrograms
Back to Fibonacci_numbers_(OCaml)
Download for Windows: single file, zip
Download for UNIX: single file, zip, tar.gz, tar.bz2
fibonacci.ml
1 (* Copyright (c) 2008 the authors listed at the following URL, and/or 2 the authors of referenced articles or incorporated external code: 3 http://en.literateprograms.org/Fibonacci_numbers_(OCaml)?action=history&offset=20080216154027 4 5 Permission is hereby granted, free of charge, to any person obtaining 6 a copy of this software and associated documentation files (the 7 "Software"), to deal in the Software without restriction, including 8 without limitation the rights to use, copy, modify, merge, publish, 9 distribute, sublicense, and/or sell copies of the Software, and to 10 permit persons to whom the Software is furnished to do so, subject to 11 the following conditions: 12 13 The above copyright notice and this permission notice shall be 14 included in all copies or substantial portions of the Software. 15 16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 21 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 22 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 24 Retrieved from: http://en.literateprograms.org/Fibonacci_numbers_(OCaml)?oldid=12494 25 *) 26 27 let rec fibonacci = function 28 | 0 -> 0 29 | 1 -> 1 30 | n when n > 1 -> fibonacci (n-1) + fibonacci (n-2) 31 | _ -> raise (Invalid_argument "Fibonacci numbers are only defined over the non-negative integers") 32 33 let iterative_fib n = 34 let rec i_fib a b = function 35 | 0 -> a 36 | 1 -> b 37 | k when k > 1 -> i_fib b (a+b) (k-1) 38 | _ -> raise (Invalid_argument "Fibonacci numbers are only defined over the non-negative integers") 39 in 40 i_fib 0 1 n 41 42 43 #load "camlp4o.cma";; 44 #load "pa_extend.cmo";; 45 46 let rec f a b = [< 'a; f b (a+b) >] 47 48 let next = parser [< 'x >] -> x 49 50 #load "nums.cma";; 51 open Big_int;; 52 53 let bfib n = 54 let rec bfib_i a b = function 55 | 0 -> a 56 | 1 -> b 57 | n when n > 1 -> bfib_i b (add_big_int a b) (n-1) 58 | _ -> raise (Invalid_argument "Fibonacci numbers are only defined over the non-negative integers") 59 in 60 bfib_i zero_big_int unit_big_int n 61 62 let rec big_f a b = [< 'a; big_f b (add_big_int a b) >] 63 let big_fibs = big_f zero_big_int unit_big_int 64 let big_next = parser [< 'x >] -> string_of_big_int x
