R/utils.R

Defines functions n_args compose reduce map flatten_list parse_function_name

parse_function_name <- function(f) {
  deparse(substitute(f))
}

flatten_list <- function(x) {
  if (is_flat_list(x)) {
    x
  } else {
    flatten_list(
      unlist(x, recursive = FALSE)
    )
  }
}

map <- function(fn) {
  function(x) {
    result <- vector(typeof(x), length(x))
    vec_names <- names(x)

    for (i in seq_along(x)) {
      result[[i]] <- fn(x[[i]])
    }

    names(result) <- vec_names
    result
  }
}

reduce <- function(fn, init) {
  function(x) {
    acc <- init

    for (i in seq_along(x)) {
      acc <- fn(acc, x[[i]])
    }

    acc
  }
}

compose <- function(...) {
  \(x) {
    Reduce(
      function(res, fn) fn(res),
      rev(list(...)),
      x
    )
  }
}

n_args <- function(fn) {
  length(
    suppressWarnings({
      formals(args(fn))
    })
  )
}
armcn/pure documentation built on Dec. 30, 2021, 12:16 a.m.