Package 'factory'

Title: Build Function Factories
Description: Function factories are functions that make functions. They can be confusing to construct. Straightforward techniques can produce functions that are fragile or hard to understand. While more robust techniques exist to construct function factories, those techniques can be confusing. This package is designed to make it easier to construct function factories.
Authors: Jon Harmon [aut, cre] , Tyler Grant Smith [ctb]
Maintainer: Jon Harmon <[email protected]>
License: MIT + file LICENSE
Version: 0.1.0.9000
Built: 2024-11-21 03:34:48 UTC
Source: https://github.com/jonthegeek/factory

Help Index


Insert Into a Function Body

Description

Insert quoted insertions at the start of a function body (after the opening of the function).

Usage

body_insert(fn_body, insertion, before = NULL)

Arguments

fn_body

The body of a function (as found via body(fun)).

insertion

A quoted expression to add at the beginning of the function.

Value

A function body with the insertion. Note: If before is specified and is not found anywhere in fn_body, fn_body is returned unaltered.

Examples

fun <- function(x) {
  x + 1
}
body_insert(body(fun), quote(x + 2))

Replace Parts of a Function Body

Description

Replace quoted targets in the body of a function with quoted replacements.

Usage

body_replace(fn_body, target, replacement)

Arguments

fn_body

The body of a function (as found via body(fun)).

target

A quoted expression to replace.

replacement

A quoted expression with which the target should be replaced.

Value

A function body with the target replaced anywhere it occurs.

Examples

fun <- function(x) {
  x^exp
}
body_replace(body(fun), quote(exp), quote(!!exp))

Easily Build Function Factories

Description

Easily Build Function Factories

Usage

build_factory(fun, ..., .pass_dots = FALSE, .internal_variables = NULL)

Arguments

fun

A function to turn into a factory.

...

Arguments for the factory function. Things on the RHS will be evaluated before building your factory unless explicitly quoted with quote. See examples.

.pass_dots

A logical indicating whether the factory should accept additional arguments (...) to pass on to methods. In order for this to work, the manufactured function *must* also include dots, and the input fun must indicate where those dots are used.

.internal_variables

A named list of additional code to run to create additional variables used by the factory.

Value

A function factory.

Examples

y <- 2
power <- build_factory(
  fun = function(x) {
    x^exponent
  },
  exponent
)
square <- power(y)
square(2)
y <- 7
square(2)

base_bins <- build_factory(
  .internal_variables = list(
    nclass_fun = switch(
      type,
      Sturges = nclass.Sturges,
      scott = nclass.scott,
      FD = nclass.FD,
      stop("Unknown type", call. = FALSE)
    )
  ),
  fun = function(x) {
    (max(x) - min(x) / nclass_fun(x))
  },
  type
)
base_bins("Sturges")