【发布时间】:2013-07-05 17:43:17
【问题描述】:
我想体验一下 R 中的函数式编程。 为此,我想编写vandermonde matrix 计算,因为它可能涉及一些构造。
在命令式风格中:
vandermonde.direct <- function (alpha, n)
{
if (!is.vector(alpha)) stop("argument alpha is not a vector")
if (!is.numeric(alpha)) stop("argument n is not a numeric vector")
m <- length(alpha)
V <- matrix(0, nrow = m, ncol = n)
V[, 1] <- rep(1, m)
j <- 2
while (j <= n) {
V[, j] <- alpha^(j - 1)
j <- j + 1
}
return(V)
}
你会如何在 R 中以函数式风格优雅地编写它?
以下不起作用:
x10 <- runif(10)
n <- 3
Reduce(cbind, aaply(seq_len(n-1),1, function (i) { function (x) {x**i}}), matrix(1,length(x10),1))
它告诉我Error: Results must have one or more dimensions. 的函数列表从i in seq_len(3-1) 到函数x -> x**i.
【问题讨论】:
-
我会使用
outer( x10, seq(0,n-1), "^" )。 -
domo arigato... 你有专门针对 FP + R 的文档吗?
-
@nicolas 我选择关注您问题的具体细节,而不是函数式编程这个极其广泛的主题。这封信将使这成为关闭的候选人。
标签: r functional-programming higher-order-functions