Skip to content

Instantly share code, notes, and snippets.

@0017031
Forked from gusty/trampoline.fsx
Created February 27, 2024 08:04
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 0017031/2711b6482940f7b625fe415f7231598e to your computer and use it in GitHub Desktop.
Save 0017031/2711b6482940f7b625fe415f7231598e to your computer and use it in GitHub Desktop.
Trampolines in F#
let trampoline f c n =
let rec loop = function
| Choice1Of2 x -> x
| Choice2Of2 x -> loop (f x)
loop (Choice2Of2 (c,n))
// Test
let factorial n =
let rec factorialT (current, n) =
if n = bigint 0 then Choice1Of2 current
else Choice2Of2 (current * n, n - 1I)
trampoline factorialT 1I n
factorial 20000I
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment