【R言語】統計解析フリーソフトR 第4章【GNU R】
レス数が950を超えています。1000を超えると書き込みができなくなります。
0966132人目の素数さん
2013/08/23(金) NY:AN:NY.AN?Reduceより
Iterate <- function(f, n = 1) function(x) Reduce(function(g, ...) g(...), rep.int(list(f), n), x, right = TRUE)
h <- function(x) 1 + 1 / x
> Iterate(h, 40)(1) == (sqrt(5) + 1) / 2
[1] TRUE
関数言語っぽく
Compose <- function(f, g) function(x) f(g(x))
nest.fun <- function(f, n){
if (n == 0) function(x) identity(x)
else Compose(f, nest.fun(f, n - 1))
}
> nest.fun(h, 40)(1) == (sqrt(5) + 1) / 2
[1] TRUE
末尾再帰かつ高速化
nest.fun <- function(f, n, acc.fun = identity){
if (n == 0) return(acc.fun)
else if (n %% 2 == 0) nest.fun(Compose(f, f), n / 2, acc.fun)
else nest.fun(f, n - 1, Compose(f, acc.fun))
}
レス数が950を超えています。1000を超えると書き込みができなくなります。