Skip to content

Instantly share code, notes, and snippets.

@espio999
espio999 / memofib.fsx
Last active July 7, 2024 23:34
F# fibonacci, call memo.fsx and fibonacci.fsx
#load "memo.fsx"
#load "fibonacci.fsx"
open memo
open fibonacci
open System.Diagnostics
let memo_fib = memoize fib
let memo_fib_tail = memoize fib_tail_recursion
@espio999
espio999 / fibonacci.fsx
Last active July 7, 2024 12:51
F# fibonacci module
module fibonacci
let rec fib n =
match n with
| 0 | 1 -> n
| n -> fib (n-1) + fib (n-2)
let fib_tail_recursion n =
let rec loop acc1 acc2 n =
match n with
@espio999
espio999 / memo.fsx
Last active July 7, 2024 23:34
F# memoize module
module memo
open System.Collections.Generic
let memoize fn =
//let cache = new System.Collections.Generic.Dictionary<_,_>()
let cache = new Dictionary<_,_>()
printfn "counter: %A" cache.Count
fun x ->
@espio999
espio999 / memofib2.fsx
Created July 7, 2024 12:20
F# fibonacci in tail recursion with memoize
let memoize fn =
let cache = new System.Collections.Generic.Dictionary<_,_>()
printfn "counter: %A" cache.Count
fun x ->
printfn "%A is received" x
match cache.TryGetValue x with
| true, v -> v
| false, _ -> let v = fn (x)
cache.Add(x,v)
@espio999
espio999 / memofib1.fsx
Created July 7, 2024 12:20
F# fibonacci with memoize
let memoize fn =
let cache = new System.Collections.Generic.Dictionary<_,_>()
printfn "counter: %A" cache.Count
fun x ->
printfn "%A is received" x
match cache.TryGetValue x with
| true, v -> v
| false, _ -> let v = fn (x)
cache.Add(x,v)
@espio999
espio999 / memoize.fsx
Created July 6, 2024 14:11
F# memoize
let memoize fn =
let cache = new System.Collections.Generic.Dictionary<_,_>()
printfn "counter: %A" cache.Count
fun x ->
printfn "%A is received" x
match cache.TryGetValue x with
| true, v -> v
| false, _ -> let v = fn (x)
cache.Add(x,v)
@espio999
espio999 / fib2.fsx
Created July 2, 2024 14:35
F# fibonacci in tail recursion
let fib n =
let rec loop acc1 acc2 n =
match n with
| 0 -> acc1
| 1 -> acc2
| _ -> loop acc2 (acc1 + acc2) (n - 1)
loop 0 1 n
fib 40 |> printfn "%A"
@espio999
espio999 / fib1.fsx
Created July 2, 2024 14:34
F# fibonacci
let rec fib n =
match n with
| 0 | 1 -> n
| n -> fib (n-1) + fib (n-2)
fib 40 |> printfn "%A"
@espio999
espio999 / pattern_matching_with_type_test.fsx
Created July 1, 2024 12:46
F# pattern matching - type test
type A() = class end
type B() = inherit A()
type C() = inherit A()
let evaluation (obj: A) =
match obj with
| :? B -> "It's a B"
| :? C -> "It's a C"
| :? A -> "It's a A"
| _ -> "nothing"
@espio999
espio999 / pattern_matching_with_type_annotation.fsx
Created July 1, 2024 12:41
F# pattern matching - type annotation
let detect1 x =
match x with
| 1 -> printfn "Found a 1!"
| (var1 : int) -> printfn "%d" var1
let my_list = [0..9]
for i in my_list do detect1 i