Skip to content

Instantly share code, notes, and snippets.

@espio999
Last active July 22, 2024 13:02
Show Gist options
  • Save espio999/7a8d089b05226fec5c4c4fffcd084e0e to your computer and use it in GitHub Desktop.
Save espio999/7a8d089b05226fec5c4c4fffcd084e0e to your computer and use it in GitHub Desktop.
F# fibonacci module
module fibonacci
open System.Collections.Generic
let rec fib n =
match n with
| 0 | 1 -> n
| n -> fib (n-1) + fib (n-2)
[<TailCall>]
let fib_memo n =
let memo = new Dictionary<_,_>()
let rec fib n =
let isExist, value = memo.TryGetValue n
if isExist then
//printf "!"
value
else
match n with
| 0 | 1 -> n
| n ->
let value = fib (n-1) + fib (n-2)
memo.Add(n, value)
value
fib n
[<TailCall>]
let fib_tail_recursion n =
let rec loop acc1 acc2 n =
match n with
| 0 -> acc1
| 1 -> acc2
| _ -> loop acc2 (acc1 + acc2) (n - 1)
loop 0 1 n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment