iterate {funprog}R Documentation

Apply a function repeatedly

Description

Apply a function to a value, then reapply the same function to the result and so on... until a condition on the result is met (or a certain number of iterations reached).

Usage

iterate(x, f, stop_fun = NULL, stop_n = Inf, accumulate = FALSE)

Arguments

x

initial value.

f

the function to apply.

stop_fun

a predicate (function) evaluated on the current result, which will stop the process if its result is TRUE. If not provided, the process will stop after stop_n iteration (see below).

stop_n

maximal number of times the function will be applied (mandatory if stop_fun is not defined).

accumulate

by default, the function returns only the last element. To get the list of all intermediate results, turn this parameter to TRUE.

Details

As it is a very generic function (x can be any type of object) and the number of computations cannot be known in advance, iterate can be quite inefficient (particularly if you use accumulate = TRUE).

Value

The last result, or the list of all results if accumulate = TRUE.

Examples

# https://en.wikipedia.org/wiki/Collatz_conjecture
syracuse <- function(x) if (x %% 2) 3 * x + 1 else x / 2
iterate(
  10,
  syracuse,
  stop_fun = function(n) n == 1,
  accumulate = TRUE
)

# https://en.wikipedia.org/wiki/H%C3%A9non_map
henon_attractor <-
  iterate(
    c(-1, 0.1),
    function(x) c(1 - 1.4 * x[1]^2 + x[2], 0.3 * x[1]),
    stop_n = 5000,
    accumulate = TRUE
  )
plot(
  sapply(henon_attractor, function(.) .[1]),
  sapply(henon_attractor, function(.) .[2]),
  pch = "."
)

[Package funprog version 0.3.0 Index]