The R Project SVN R

Rev

Rev 59039 | Rev 69538 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
42333 ripley 1
% File src/library/methods/man/setGeneric.Rd
2
% Part of the R package, http://www.R-project.org
59039 ripley 3
% Copyright 1995-2007 R Core Team
42333 ripley 4
% Distributed under GPL 2 or later
5
 
15357 jmc 6
\name{setGeneric}
56186 murdoch 7
\alias{setGeneric}
16764 jmc 8
\alias{setGroupGeneric}
15357 jmc 9
\title{Define a New Generic Function}
10
\description{
45824 jmc 11
  Create a new generic function of the given name, that is, a function
12
  that dispatches methods according to the classes of the arguments,
13
  from among the formal methods defined for this function.
15357 jmc 14
}
15
\usage{
44243 ripley 16
setGeneric(name, def= , group=list(), valueClass=character(),
17
           where= , package= , signature= , useAsDefault= ,
46546 jmc 18
           genericFunction= , simpleInheritanceOnly = )
16764 jmc 19
 
26530 maechler 20
setGroupGeneric(name, def= , group=list(), valueClass=character(),
21
                knownMembers=list(), package= , where= )
15357 jmc 22
}
23
\arguments{
45824 jmc 24
  \item{name}{ The character string name of the generic function.
49719 maechler 25
    The simplest (and recommended) call, \code{setGeneric(name)},
45824 jmc 26
    looks for a function with this name and creates a corresponding
58136 jmc 27
    generic function,  if the function found was not generic.  In the
28
    latter case, the existing function becomes the default method.
15571 ripley 29
  }
50786 maechler 30
  \item{def}{An optional function object, defining the generic.
58136 jmc 31
    Don't supply this argument if you want to turn an existing non-generic
32
    function into a generic. In this case, you usually want to use the
33
    simple call with one argument.
26530 maechler 34
 
58136 jmc 35
    Do supply \code{def} if there is no
36
    current function of this name or for some reason you do not want
37
    to use that function to define the generic. In that case, the
61433 ripley 38
    formal arguments and
58136 jmc 39
    default values for the generic are taken from \code{def}.  In most
40
    cases, the body of \code{def} will then define the default method,
41
    as the existing function did in the one-argument call.
42
 
43
    If you want to create a new generic function with \emph{no}
44
    default method, then \code{def} should be only a call to
45
    \code{\link{standardGeneric}} with the same character string as
46
    \code{name}.
47
 
61433 ripley 48
 
15357 jmc 49
  }
45824 jmc 50
  \item{group}{ Optionally, a character string giving the name of the group
51
    generic function to which this function belongs.    See
52
    \link{Methods} for details of group generic functions in method selection.
15571 ripley 53
  }
45824 jmc 54
  \item{valueClass}{ An optional character vector of one or more class
50786 maechler 55
    names.  The value returned by the generic function must
42679 ripley 56
    have (or extend) this class, or one of the classes; otherwise,
45824 jmc 57
    an error is generated.
42679 ripley 58
  }
20092 jmc 59
  \item{package}{ The name of the package with which this function is
42679 ripley 60
    associated.  Usually determined automatically (as the package
61
    containing the non-generic version if there is one, or else the
62
    package where this generic is to be saved).
63
  }
16707 jmc 64
  \item{where}{ Where to store the resulting initial methods definition,
65
    and possibly the generic function; by
20092 jmc 66
    default, stored into the top-level environment.
15571 ripley 67
  }
21345 jmc 68
  \item{signature}{
50786 maechler 69
    Optionally, the vector of names, from among the formal arguments to
70
    the function, that can appear in the signature of methods for this
71
    function, in calls to \code{\link{setMethod}}.  If \dots is one of
72
    the formal arguments, it is treated specially.  Starting with
73
    version 2.8.0 of \R, \dots may be signature of the generic function.
74
    Methods will then be selected if their signature matches all the
75
    \dots arguments.  See the documentation for topic \link{dotsMethods}
76
    for details.  In the present version, it is not possible to mix
77
    \dots and other arguments in the signature (this restriction may be
78
    lifted in later versions).
46314 jmc 79
 
50786 maechler 80
    By default, the signature is inferred from the implicit generic
81
    function corresponding to a non-generic function.  If no implicit
82
    generic function has been defined, the default is all the formal
83
    arguments except \dots, in the order they appear in the function
84
    definition. In the case that \dots is the only formal argument, that
85
    is also the default signature.  To use \dots as the signature in a
86
    function that has any other arguments, you must supply the signature
87
    argument explicitly.  See the \dQuote{Implicit Generic} section
88
    below for more details.
15571 ripley 89
  }
18976 jmc 90
  \item{useAsDefault}{
58136 jmc 91
    Override the usual choice of default argument.
50786 maechler 92
    Argument \code{useAsDefault} can be supplied, either as a function
93
    to use for the default, or as a logical value.
58136 jmc 94
    This argument is now rarely needed.
95
    See
50786 maechler 96
    the section on details.
42679 ripley 97
  }
46546 jmc 98
  \item{simpleInheritanceOnly}{
50786 maechler 99
    Supply this argument as \code{TRUE} to require that methods selected
100
    be inherited through simple inheritance only; that is, from
101
    superclasses specified in the \code{contains=} argument to
102
    \code{\link{setClass}}, or by simple inheritance to a class union or
103
    other virtual class.  Generic functions should require simple
104
    inheritance if they need to be assured that they get the complete
105
    original object, not one that has been transformed.  Examples of
106
    functions requiring simple inheritance are \code{\link{initialize}},
107
    because by definition it must return an object from the same class
108
    as its argument, and \code{\link{show}}, because it claims to give a
109
    full description of the object provided as its argument.
46546 jmc 110
  }
50786 maechler 111
  \item{genericFunction}{Don't use; for (possible) internal use only.}
18558 jmc 112
 
16802 jmc 113
  \item{knownMembers}{
42299 ripley 114
    (For \code{setGroupGeneric} only.)  The names of functions that are
115
    known to be members of this group.  This information is used to
116
    reset cached definitions of the member generics when information
117
    about the group generic is changed.
42679 ripley 118
  }
15357 jmc 119
}
45824 jmc 120
\section{Basic Use}{
15357 jmc 121
  The \code{setGeneric} function is called to initialize a generic
50786 maechler 122
  function as preparation for defining some methods for that function.
15357 jmc 123
 
124
  The simplest and most common situation is that \code{name} is already
50786 maechler 125
  an ordinary non-generic non-primitive function, and you now want to
126
  turn this function into a generic.  In this case you will most often
127
  supply only \code{name}, for example:
16764 jmc 128
 
45824 jmc 129
    \code{setGeneric("colSums")}
130
 
50786 maechler 131
  There must be an existing function of this name, on some attached
132
  package (in this case package \code{"base"}).  A generic version of
133
  this function will be created in the current package (or in the global
134
  environment if the call to \code{setGeneric()} is from an ordinary
135
  source file or is entered on the command line).  The existing function
136
  becomes the default method, and the package slot of the new generic
137
  function is set to the location of the original function
138
  (\code{"base"} in the example).  It's an important feature that the
139
  same generic function definition is created each time, depending in
140
  the example only on the definition of \code{print} and where it is
141
  found.  The \code{signature} of the generic function, defining which
142
  of the formal arguments can be used in specifying methods, is set by
143
  default to all the formal arguments except \dots.
45824 jmc 144
 
50786 maechler 145
  Note that calling \code{setGeneric()} in this form is not strictly
146
  necessary before calling \code{setMethod()} for the same function.  If
147
  the function specified in the call to \code{setMethod} is not generic,
148
  \code{setMethod} will execute the call to \code{setGeneric} itself.
149
  Declaring explicitly that you want the function to be generic can be
150
  considered better programming style; the only difference in the
151
  result, however, is that not doing so produces a message noting the
152
  creation of the generic function.
45824 jmc 153
 
50786 maechler 154
  You cannot (and never need to) create an explicit generic version of
155
  the primitive functions in the base package.  Those which can be
156
  treated as generic functions have methods selected and dispatched from
157
  the internal C code, to satisfy concerns for efficiency, and the
158
  others cannot be made generic.  See the section on Primitive Functions
159
  below.
45824 jmc 160
 
50786 maechler 161
  The description above is the effect when the package that owns the
162
  non-generic function has not created an implicit generic version.
163
  Otherwise, it is this implicit generic function that is used. See the
164
  section on Implicit Generic Functions below.  Either way, the
165
  essential result is that the \emph{same} version of the generic
166
  function will be created each time.
45824 jmc 167
 
50786 maechler 168
  The second common use of \code{setGeneric()} is to create a new
169
  generic function, unrelated to any existing function, and frequently
170
  having no default method.  In this case, you need to supply a skeleton
171
  of the function definition, to define the arguments for the function.
172
  The body of a generic function is usually a standard form,
173
  \code{standardGeneric(name)} where \code{name} is the quoted name of
174
  the generic function.  When calling \code{setGeneric} in this form,
175
  you would normally supply the \code{def} argument as a function of
176
  this form.  See the second and third examples below.
18976 jmc 177
 
50786 maechler 178
  The \code{useAsDefault} argument controls the default method for the
179
  new generic.  If not told otherwise, \code{setGeneric} will try to
180
  find a non-generic version of the function to use as a default.  So,
181
  if you do have a suitable default method, it is often simpler to first
182
  set this up as a non-generic function, and then use the one-argument
183
  call to \code{setGeneric} at the beginning of this section.  See the
184
  first example in the Examples section below.
18976 jmc 185
 
50786 maechler 186
  If you \emph{don't} want the existing function to be taken as default,
187
  supply the argument \code{useAsDefault}.  That argument can be the
188
  function you want to be the default method, or \code{FALSE} to force
189
  no default (i.e., to cause an error if there is no direct or inherited
190
  method selected for a call to the function).
45824 jmc 191
}
192
\section{Details}{
58136 jmc 193
  The great majority of calls to \code{setGeneric()} should either
194
  have one argument to ensure that an existing function can have
195
  methods, or arguments \code{name} and \code{def} to create a new
196
  generic function and optionally a default method.  If that's not
197
  what you plan to do, read on.
198
 
50786 maechler 199
  If you want to change the behavior of an existing function (typically,
200
  one in another package) when you create a generic version, you must
201
  supply arguments to \code{setGeneric} correspondingly.  Whatever
202
  changes are made, the new generic function will be assigned with a
203
  package slot set to the \emph{current} package, not the one in which
204
  the non-generic version of the function is found.  This step is
205
  required because the version you are creating is no longer the same as
206
  that implied by the function in the other package.  A message will be
207
  printed to indicate that this has taken place and noting one of the
58136 jmc 208
  differences between the two functions.  It tends to be a bad idea,
209
  because the two versions are now competing for methods, with many
210
  chances for mistakes in programming.
18976 jmc 211
 
50786 maechler 212
  The body of a generic function usually does nothing except for
213
  dispatching methods by a call to \code{standardGeneric}.  Under some
214
  circumstances you might just want to do some additional computation in
215
  the generic function itself.  As long as your function eventually
216
  calls \code{standardGeneric} that is permissible (though perhaps not a
217
  good idea, in that it may make the behavior of your function less easy
218
  to understand).  If your explicit definition of the generic function
18976 jmc 219
  does \emph{not} call \code{standardGeneric} you are in trouble,
50786 maechler 220
  because none of the methods for the function will ever be dispatched.
20676 jmc 221
 
42656 ripley 222
  By default, the generic function can return any object.  If
223
  \code{valueClass} is supplied, it should be a vector of class names;
224
  the value returned by a method is then required to satisfy
225
  \code{is(object, Class)} for one of the specified classes.  An empty
226
  (i.e., zero length) vector of classes means anything is allowed.  Note
227
  that more complicated requirements on the result can be specified
228
  explicitly, by defining a non-standard generic function.
18976 jmc 229
 
42679 ripley 230
  The \code{setGroupGeneric} function behaves like \code{setGeneric}
231
  except that it constructs a group generic function, differing in two
232
  ways from an ordinary generic function.  First, this function cannot
233
  be called directly, and the body of the function created will contain
50786 maechler 234
  a stop call with this information.  Second, the group generic function
235
  contains information about the known members of the group, used to
236
  keep the members up to date when the group definition changes, through
237
  changes in the search list or direct specification of methods, etc.
15357 jmc 238
}
45824 jmc 239
\section{Implicit Generic Functions}{
50786 maechler 240
  Saying that a non-generic function \dQuote{is converted to a generic}
241
  is more precisely state that the function is converted to the
242
  corresponding \emph{implicit} generic function.  If no special action
243
  has been taken, any function corresponds implicitly to a generic
244
  function with the same arguments, in which all arguments other than
245
  \dots can be used.  The signature of this generic function is the
246
  vector of formal arguments, in order, except for \dots.
45824 jmc 247
 
50786 maechler 248
  The source code for a package can define an implicit generic function
249
  version of any function in that package (see \link{implicitGeneric}
250
  for the mechanism).  You can not, generally, define an implicit
251
  generic function in someone else's package. The usual reason for
252
  defining an implicit generic is to prevent certain arguments from
253
  appearing in the signature, which you must do if you want the
254
  arguments to be used literally or if you want to enforce lazy
255
  evaluation for any reason.  An implicit generic can also contain some
256
  methods that you want to be predefined; in fact, the implicit generic
257
  can be any generic version of the non-generic function.  The implicit
258
  generic mechanism can also be used to prohibit a generic version (see
259
  \code{\link{prohibitGeneric}}).
45824 jmc 260
 
50786 maechler 261
  Whether defined or inferred automatically, the implicit generic will
262
  be compared with the generic function that \code{setGeneric} creates,
263
  when the implicit generic is in another package.  If the two functions
264
  are identical, then the \code{package} slot of the created generic
265
  will have the name of the package containing the implicit generic.
266
  Otherwise, the slot will be the name of the package in which the
267
  generic is assigned.
45824 jmc 268
 
50786 maechler 269
  The purpose of this rule is to ensure that all methods defined for a
270
  particular combination of generic function and package names
271
  correspond to a single, consistent version of the generic function.
272
  Calling \code{setGeneric} with only \code{name} and possibly
273
  \code{package} as arguments guarantees getting the implicit generic
274
  version, if one exists.
45824 jmc 275
 
50786 maechler 276
  Including any of the other arguments can force a new, local version of
277
  the generic function.  If you don't want to create a new version,
278
  don't use the extra arguments.
45824 jmc 279
}
19473 jmc 280
\section{Generic Functions and Primitive Functions}{
41161 maechler 281
  A number of the basic \R functions are specially implemented as
50786 maechler 282
  primitive functions, to be evaluated directly in the underlying C code
283
  rather than by evaluating an \R language definition.  Most have
42299 ripley 284
  implicit generics (see \code{\link{implicitGeneric}}), and become
285
  generic as soon as methods (including group methods) are defined on
286
  them.  Others cannot be made generic.
19473 jmc 287
 
50786 maechler 288
  Even when methods are defined for such functions, the generic version
289
  is not visible on the search list, in order that the C version
290
  continues to be called.  Method selection will be initiated in the C
291
  code.  Note, however, that the result is to restrict methods for
292
  primitive functions to signatures in which at least one of the classes
293
  in the signature is a formal S4 class.
45824 jmc 294
 
295
  To see the generic version of a primitive function, use
296
  \code{\link{getGeneric}(name)}.  The function
297
  \code{\link{isGeneric}} will tell you whether methods are defined
298
  for the function in the current session.
299
 
48062 jmc 300
  Note that S4 methods can only be set on those primitives which are
301
  \sQuote{\link{internal generic}}, plus \code{\%*\%}.
19473 jmc 302
}
15357 jmc 303
\value{
19029 hornik 304
  The \code{setGeneric} function exists for its side effect: saving the
305
  generic function to allow methods to be specified later.  It returns
306
  \code{name}.
15357 jmc 307
}
308
\references{
45824 jmc 309
 Chambers, John M. (2008)
310
 \emph{Software for Data Analysis: Programming with R}
311
  Springer.  (For the R version.)
15357 jmc 312
 
45824 jmc 313
 Chambers, John M. (1998)
314
 \emph{Programming with Data}
315
 Springer (For the original S4 version.)
15357 jmc 316
}
20676 jmc 317
\examples{
26000 ripley 318
\dontshow{
42679 ripley 319
setClass("track", representation(x="numeric", y="numeric"))
15357 jmc 320
}
20676 jmc 321
 
45824 jmc 322
## create a new generic function, with a default method
58136 jmc 323
setGeneric("props", function(object) attributes(object))
45824 jmc 324
 
325
## A new generic function with no default method
326
setGeneric("increment",
327
  function(object, step, ...)
328
    standardGeneric("increment")
329
)
330
 
331
 
20676 jmc 332
###   A non-standard generic function.  It insists that the methods
333
###   return a non-empty character vector (a stronger requirement than
334
###    valueClass = "character" in the call to setGeneric)
335
 
26530 maechler 336
setGeneric("authorNames",
20676 jmc 337
    function(text) {
338
      value <- standardGeneric("authorNames")
339
      if(!(is(value, "character") && any(nchar(value)>0)))
340
        stop("authorNames methods must return non-empty strings")
341
      value
342
      })
343
 
26000 ripley 344
\dontshow{
20676 jmc 345
setMethod("authorNames", "character", function(text)text)
346
 
49727 maechler 347
tryIt <- function(expr) tryCatch(expr, error = function(e) e)
39651 maechler 348
stopifnot(identical(authorNames(c("me", "you")), c("me", "you")),
49727 maechler 349
          is(tryIt(authorNames(character())), "error"), # empty value
350
          is(tryIt(authorNames(NULL)), "error"))        # no default method
20676 jmc 351
}
352
 
19474 jmc 353
## An example of group generic methods, using the class
51844 maechler 354
## "track"; see the documentation of \link{setClass} for its definition
19474 jmc 355
 
39651 maechler 356
## define a method for the Arith group
19474 jmc 357
 
26530 maechler 358
setMethod("Arith", c("track", "numeric"),
39651 maechler 359
 function(e1, e2) {
19474 jmc 360
  e1@y <- callGeneric(e1@y , e2)
361
  e1
362
})
363
 
26530 maechler 364
setMethod("Arith", c("numeric", "track"),
39651 maechler 365
 function(e1, e2) {
20676 jmc 366
  e2@y <- callGeneric(e1, e2@y)
367
  e2
368
})
19474 jmc 369
 
39651 maechler 370
## now arithmetic operators  will dispatch methods:
19474 jmc 371
 
41508 ripley 372
t1 <- new("track", x=1:10, y=sort(stats::rnorm(10)))
20676 jmc 373
 
19474 jmc 374
t1 - 100
20676 jmc 375
1/t1
19474 jmc 376
 
26000 ripley 377
\dontshow{
20676 jmc 378
removeGeneric("authorNames")
379
removeClass("track")
380
removeMethods("Arith")
45824 jmc 381
removeGeneric("props")
382
removeGeneric("increment")
19474 jmc 383
}
384
}
15571 ripley 385
\seealso{
46314 jmc 386
  \code{\link{Methods}} and the links there for a general discussion,
387
  \code{\link{dotsMethods}} for methods that dispatch on
46315 jmc 388
  \dQuote{\dots}, and \code{\link{setMethod}} for method definitions.
15571 ripley 389
}
390
\keyword{ programming }
391
\keyword{ methods }