问题 R中的递归组合函数?


我想在R中创建一个函数“compose”,它将构成作为参数给出的任意数量的函数。

到目前为止,我已经通过定义一个函数“of”来完成这个,该函数组成两个参数,然后减少这个:

of <- function(f,g) function(x) f(g(x))
id <- function(x) x

compose <- function(...) {
  argms = c(...)
  Reduce(of,argms,id)
}

这似乎工作得很好,但是因为我正在学习R,我想我会尝试用一种明确的递归方式来编写它,即放弃使用Reduce,这就像你在Scheme中做的那样:

(define (compose . args)
  (if (null? args) identity
      ((car args) (apply compose (cdr args)))))

我遇到了许多障碍,目前主要的障碍似乎是论证的第一个要素没有被认为是一种功能。到目前为止我的弱尝试:

comp <- function(...) {
  argms <- list(...)
  len <- length(argms)
  if(len==0) { return(id) }
  else {
    (argms[1])(do.call(comp,argms[2:len])) 
  }
}

吐出: Error in comp(sin, cos, tan) : attempt to apply non-function

必须有一些优雅的方式来做到这一点,这让我望而却步。有什么建议么?


12282
2017-09-23 05:07


起源

该 purrr package包含另一个替代方法,它不使用Reduce或递归。由于您正在学习R,它可能会为您的任务提供额外的洞察力: github.com/tidyverse/purrr/blob/master/R/compose.R - Artem Sokolov
@Artem Sokolov:这是一个有趣的实现 - 迭代和积累到一个可变变量。有点像我所说的那样(递归,不可变)完全相反,但仍然很好看,特别是在学习的时候。感谢您麻烦地链接它! - Alex Gian


答案:


1) 尝试这个:

comp1 <- function(f, ...) {
  if (missing(f)) identity
  else function(x) f(comp1(...)(x))
}


# test

comp1(sin, cos, tan)(pi/4)
## [1] 0.5143953

# compose is defined in the question
compose(sin, cos, tan)(pi/4)
## [1] 0.5143953

functional::Compose(tan, cos, sin)(pi/4)
## [1] 0.5143953

sin(cos(tan(pi/4)))
## [1] 0.5143953

library(magrittr)
(pi/4) %>% tan %>% cos %>% sin
## [1] 0.5143953

(. %>% tan %>% cos %>% sin)(pi/4)
## [1] 0.5143953

1A) (1)的变体使用 Recall 是:

comp1a <- function(f, ...) {
  if (missing(f)) identity
  else {
    fun <- Recall(...)
    function(x) f(fun(x))
  }
}

comp1a(sin, cos, tan)(pi/4)
## [1] 0.5143953

2) 这是另一个实现:

comp2 <- function(f, g, ...) {
  if (missing(f)) identity
  else if (missing(g)) f
  else Recall(function(x) f(g(x)), ...)
}

comp2(sin, cos, tan)(pi/4)
## [1] 0.5143953

3) 此实现更接近问题中的代码。它利用了 of 在问题中定义:

comp3 <- function(...) {
  if(...length() == 0) identity
  else of(..1, do.call("comp3", list(...)[-1]))
}
comp3(sin, cos, tan)(pi/4)
## [1] 0.5143953

11
2017-09-23 12:08



我删除了笔记。再看一遍就是问题所在 Recall 不是直接在顶级函数内,而是在...中定义的匿名函数内 else 腿。 - G. Grothendieck
@ G.Grothendieck那很好,谢谢,虽然我认为例子(1)最接近原始代码,比(3)更多。我特意看着不必使用 of,这基本上是一种解决方法。感谢包括示例(2),我花了一些时间来绕过它,但帮助我准确理解Recall的作用。答案被接受为基本完成。 - Alex Gian
我想你的意思是(1)最接近你要找的东西。示例(3)更接近问题中提供的代码。它使用相同的签名并选择第一个元素和剩余的元素 of 它使用 do.call 和问题中的代码一样。 - G. Grothendieck


一个问题是,如果 len==1, 然后 argms[2:len] 返回长度为2的列表;尤其是,

> identical(argms[2:1], list(NULL, argms[[1]]))
[1] TRUE

要修复它,你可以使用删除列表的第一个元素 argms[-1]

你还需要利用你的 of  功能,因为你可能注意到了 sin(cos) 返回错误而不是函数。把它们放在一起我们得到:

comp <- function(...) {
  argms <- c(...)
  len <- length(argms)
  if(len==1) { return(of(argms[[1]], id)) }
  else {
    of(argms[[1]], comp(argms[-1]))
  }
}

> comp(sin, cos, tan)(1)
[1] 0.0133878
> compose(sin, cos, tan)(1)
[1] 0.0133878

2
2017-09-23 06:52





滚动自己的功能组合的另一种方法是使用 完形 包,它提供组合作为高阶函数, compose(),作为中缀运营商, %>>>%。 (对于这些阅读相同,功能由...组成 左到右。)

基本用法很简单:

library(gestalt)

f <- compose(tan, cos, sin)  # apply tan, then cos, then sin
f(pi/4)
#> [1] 0.514395258524

g <- tan %>>>% cos %>>>% sin
g(pi/4)
#> [1] 0.514395258524

但是你获得了很多额外的灵活性:

## You can annotate composite functions and apply list methods
f <- first: tan %>>>% cos %>>>% sin
f[[1]](pi/4)
#> [1] 1
f$first(pi/4)
#> [1] 1

## magrittr %>% semantics, such as implicity currying, is supported
scramble <- sample %>>>% paste(collapse = "")
set.seed(1); scramble(letters, 5)
#> [1] "gjnue"

## Compositions are list-like; you can inspect them using higher-order functions
stepwise <- lapply(`%>>>%`, print) %>>>% compose
stepwise(f)(pi/4)
#> [1] 1
#> [1] 0.540302305868
#> [1] 0.514395258524

## formals are preserved
identical(formals(scramble), formals(sample))
#> [1] TRUE

关于R中的函数调用,您应该记住的一件事是它们的成本不可忽略。与文字功能组合不同, compose() (和 %>>>%)当被召唤时弄平构图。特别是,以下调用产生相同的功能, 操作上

fs <- list(tan, cos, sin)

## compose(tan, cos, sin)
Reduce(compose, fs)
Reduce(`%>>>%`, fs)
compose(fs)
compose(!!!fs)  # tidyverse unquote-splicing

2
2017-09-24 12:34





这是一个返回易于理解的函数的解决方案

func <- function(f, ...){
  cl <- match.call()
  if(length(cl) == 2L)
    return(eval(bquote(function(...) .(cl[[2L]]))))

  le <- max(which(sapply(cl, inherits, "name")))
  if(le == length(cl)){
    tmp <- cl[le]
    tmp[[2L]] <- quote(...)
    cl[[length(cl)]] <- tmp

  } else if(le == length(cl) - 1L){
    tmp <- cl[le]
    tmp[[2L]] <- cl[[le + 1L]]
    cl[[le]] <- tmp
    cl[[le + 1L]] <- NULL

  } else
    stop("something is wrong...")

  eval(cl)
}

func(sin, cos, tan) # clear what the function does
#R function (...) 
#R sin(cos(tan(...)))
#R <environment: 0x000000001a189778>
func(sin, cos, tan)(pi/4) # gives correct value
#R [1] 0.5143953

人们可能要调整 sapply(cl, inherits, "name") 排成更通用的东西......


0
2017-09-23 19:49





这是一个从调用构建函数的解决方案,它提供类似于Benjamin的可读输出:

compose_explicit <- function(...){
  funs <- as.character(match.call()[-1])
  body <- Reduce(function(x,y) call(y,x), rev(funs), init = quote(x))
  eval.parent(call("function",as.pairlist(alist(x=)),body))
}
compose_explicit(sin, cos, tan)
# function (x) 
# sin(cos(tan(x)))

compose_explicit(sin, cos, tan)(pi/4)
# [1] 0.5143953

看起来非常强大:

compose_explicit()
# function (x) 
# x

compose_explicit(sin)
# function (x) 
# sin(x)

而且不相关但有用,这里是代码 purrr:compose :

#' Compose multiple functions
#'
#' @param ... n functions to apply in order from right to left.
#' @return A function
#' @export
#' @examples
#' not_null <- compose(`!`, is.null)
#' not_null(4)
#' not_null(NULL)
#'
#' add1 <- function(x) x + 1
#' compose(add1, add1)(8)
compose <- function(...) {
  fs <- lapply(list(...), match.fun)
  n <- length(fs)

  last <- fs[[n]]
  rest <- fs[-n]

  function(...) {
    out <- last(...)
    for (f in rev(rest)) {
      out <- f(out)
    }
    out
  }
}

0
2017-09-24 22:19