zeallot (version 0.1.0)

destructure: Destructure an object

Description

destructure is used during unpacking assignment to coerce an object into a list. Individual elements of the list are assigned to names on the left-hand side of the unpacking assignment expression.

Usage

destructure(x)

Arguments

x

An R object.

Details

If x is atomic destructure expects length(x) to be 1. If a vector with length greater than 1 is passed to destructure an error is raised.

New implementations of destructure can be very simple. A new destructure implementation might only strip away the class of a custom object and return the underlying list structure. Alternatively, an object might destructure into a nested set of values and may require a more complicated implementation. In either case, new implementations must return a list object so %<-% can handle the returned value(s).

See Also

%<-%

Examples

Run this code
# NOT RUN {
# data frames become a list of columns
destructure(
  data.frame(x = 0:4, y = 5:9)
)

# strings are split into list of characters
destructure("abcdef")

# dates become list of year, month, and day
destructure(Sys.Date())

# create a new destructure implementation
shape <- function(sides = 4, color = "red") {
  structure(
    list(sides = sides, color = color),
    class = "shape"
  )
}

# }
# NOT RUN {
# cannot destructure the shape object yet
c(sides, color) %<-% shape()
# }
# NOT RUN {
# implement `destructure` for shapes
destructure.shape <- function(x) {
  list(x$sides, x$color)
}

# now we can destructure shape objects
c(sides, color) %<-% destructure(shape())

sides  # 4
color  # "red"

c(sides, color) %<-% destructure(shape(3, "green"))

sides  # 3
color  # 'green'

# }

Run the code above in your browser using DataLab