Skip to content

Instantly share code, notes, and snippets.

@tjmahr
Created January 5, 2024 14:55
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 tjmahr/222d1da9b54ef837835f3232d7c780c5 to your computer and use it in GitHub Desktop.
Save tjmahr/222d1da9b54ef837835f3232d7c780c5 to your computer and use it in GitHub Desktop.
mutual recursion
is_even <- function(n) {
if (n == 0) list(TRUE, sys.nframe()) else Tailcall(is_odd, n - 1)
}
is_odd <- function(n) {
if (n == 0) list(FALSE, sys.nframe()) else Tailcall(is_even, n - 1)
}
is_odd(30)
naive_is_even <- function(n) {
if (n == 0) list(TRUE, sys.nframe()) else naive_is_odd(n - 1)
}
naive_is_odd <- function(n) {
if (n == 0) list(FALSE, sys.nframe()) else naive_is_even(n - 1)
}
naive_is_odd(30)
is_odd(10)
is_even(10)
is_odd(30)
is_even(1000)[[1]]
naive_is_even(10000)[[1]]
is_even(10000)[[1]]
is_odd(9)
is_even(9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment