|
| 1 | +# [My OCaml Practice](../README.md#my-ocaml-practice) |
| 2 | + |
| 3 | + |
| 4 | +### References |
| 5 | + |
| 6 | +- https://ocaml.org/ |
| 7 | +- https://en.wikipedia.org/wiki/OCaml |
| 8 | + |
| 9 | + |
| 10 | +### \<Note> |
| 11 | + |
| 12 | +- Execute using *Version 5.0.0* in [JDoodle](https://www.jdoodle.com/compile-ocaml-online), unless otherwise specified |
| 13 | + |
| 14 | + |
| 15 | +### \<List> |
| 16 | + |
| 17 | +- [Fibonacci Sequence (2024.12.30)](#fibonacci-sequence-20241230) |
| 18 | + |
| 19 | + |
| 20 | +## [Fibonacci Sequence (2024.12.30)](#list) |
| 21 | + |
| 22 | +- Generate the Fibonacci sequence using regular recursive, tail-recursive and botthom-up methods |
| 23 | +- Code and Output |
| 24 | + <details> |
| 25 | + <summary>Code : FibonacciSequence.ml</summary> |
| 26 | + |
| 27 | + ```ocaml |
| 28 | + (* 1. Standard recursive method *) |
| 29 | + let rec fib_recursive n = |
| 30 | + if n <= 2 then 1 |
| 31 | + else fib_recursive (n - 1) + fib_recursive (n - 2) |
| 32 | +
|
| 33 | + (* 2. Tail recursive method *) |
| 34 | + let fib_tail_recursive n = |
| 35 | + let rec aux n a b = |
| 36 | + match n with |
| 37 | + | 1 -> a |
| 38 | + | 2 -> b |
| 39 | + | _ -> aux (n - 1) b (a + b) |
| 40 | + in aux n 1 1 |
| 41 | +
|
| 42 | + (* 3. Bottom-up method *) |
| 43 | + let fib_bottom_up n = |
| 44 | + if n <= 2 then 1 |
| 45 | + else |
| 46 | + let rec loop a b count = |
| 47 | + if count = n then b |
| 48 | + else loop b (a + b) (count + 1) |
| 49 | + in loop 1 1 2 |
| 50 | + ``` |
| 51 | + ```ocaml |
| 52 | + (* Function to print Fibonacci sequences *) |
| 53 | + let print_fib_sequence name sequence = |
| 54 | + Printf.printf "%s : %s\n" name (String.concat ", " (List.map string_of_int sequence)) |
| 55 | + ``` |
| 56 | + ```ocaml |
| 57 | + (* Calculate and print the first 10 terms of the Fibonacci sequence using each method *) |
| 58 | + let () = |
| 59 | + let range = List.init 10 (fun x -> x + 1) in |
| 60 | + print_fib_sequence "Standard Recursive Method" (List.map fib_recursive range); |
| 61 | + print_fib_sequence "Tail Recursive Method " (List.map fib_tail_recursive range); |
| 62 | + print_fib_sequence "Bottom-up Method " (List.map fib_bottom_up range) |
| 63 | + ``` |
| 64 | + </details> |
| 65 | + <details open=""> |
| 66 | + <summary>Output</summary> |
| 67 | + |
| 68 | + ```ocaml |
| 69 | + Standard Recursive Method : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 |
| 70 | + Tail Recursive Method : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 |
| 71 | + Bottom-up Method : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 |
| 72 | + ``` |
| 73 | + </details> |
0 commit comments