@@ -1,11 +1,43 @@
1module Trampoline (Trampoline, trampoline)
1module Trampoline (Trampoline, trampoline)
4+{-| Trampolining loops for unbounded recursion.
5+Since most javascript implementations lack tail-call elimination, deeply tail-recursive functions will result in a stack overflow.
8+fac' : Int -> Int -> Int
11+ else fac' (n - 1) (n * acc)
17+main = asText <| fac 1000000000000
20+Trampolining allows for long-running tail-recursive loops to be run without pushing calls onto the stack:
22+facT : Int -> Int -> Trampoline Int
23+facT n acc = Trampoline <| if n <= 0
25+ else Right <| \() -> facT (n - 1) (n * acc)
27+fac n = trampoline <| facT n 0
29+-- Doesn't stack overflow
30+main = asText <| fac 1000000000000
33+@docs Trampoline, trampoline
5import Native.Trampoline
35import Native.Trampoline
6import open Either
36import open Either
38+{-| A computation that might loop. A trampoline is either the resulting value or a thunk that needs to be run more. -}
8data Trampoline a = Trampoline (Either a (() -> Trampoline a))
39data Trampoline a = Trampoline (Either a (() -> Trampoline a))
41+{-| Run a trampolining loop in constant space. -}
10trampoline : Trampoline a -> a
42trampoline : Trampoline a -> a
11trampoline = Native.Trampoline.trampoline
43trampoline = Native.Trampoline.trampoline