Skip to content

Instantly share code, notes, and snippets.

@theburningmonk
Last active January 4, 2016 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theburningmonk/1d90b466a530698a3127 to your computer and use it in GitHub Desktop.
Save theburningmonk/1d90b466a530698a3127 to your computer and use it in GitHub Desktop.
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
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