Skip to content

Instantly share code, notes, and snippets.

@TheSeamau5
Created January 24, 2015 23:43
Show Gist options
  • Save TheSeamau5/99c07d322805153ac212 to your computer and use it in GitHub Desktop.
Save TheSeamau5/99c07d322805153ac212 to your computer and use it in GitHub Desktop.
A neat construct to loop in Elm without worrying about stack problems
loop : a -> (a -> Bool) -> (a -> a) -> (a -> b) -> b
loop start condition update return =
trampoline <|
loop' start condition update return
loop' : a -> (a -> Bool) -> (a -> a) -> (a -> b) -> Trampoline b
loop' start condition update return =
case condition start of
True -> Done (return start)
False ->
Continue (\() ->
loop' (update start) condition update return
)
go acc n =
loop {acc = acc, n = n} -- Initial state of variables
(\{n} -> n == 0) -- stopping condition
(\{acc, n} -> {acc = acc + 1, n = n - 1}) -- update variables
.acc -- return function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment