-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdestructure.Rd
72 lines (61 loc) · 1.83 KB
/
destructure.Rd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/destructure.R
\name{destructure}
\alias{destructure}
\title{Destructure an object}
\usage{
destructure(x)
}
\arguments{
\item{x}{An \R object.}
}
\description{
\code{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.
}
\details{
If \code{x} is atomic \code{destructure} expects \code{length(x)} to be 1. If a vector with
length greater than 1 is passed to \code{destructure} an error is raised.
New implementations of \code{destructure} can be very simple. A new
\code{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 \code{\%<-\%} can handle the returned value(s).
}
\examples{
# 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"
)
}
\dontrun{
# cannot destructure the shape object yet
c(sides, color) \%<-\% shape()
}
# 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'
}
\seealso{
\code{\link{\%<-\%}}
}