Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
open System.Collections.Generic
let memoize f =
let cache = Dictionary<_, _>()
fun x ->
match cache.TryGetValue x with
| true, res -> res
| _ ->
let res = f x
cache.[x] <- res
let next n = if n%2L = 0L then n/2L else 3L*n+1L
let rec collatzLengthCached =
let loop start =
let mutable current = start
if current > 1L
then 1 + collatzLengthCached (next current)
else 1
memoize loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment