Skip to content

overloading + operator for chars

2 messages · Albert-Jan Roskam, Martin Morgan

#
On 11/02/2011 06:52 AM, Albert-Jan Roskam wrote:
Hi -- I think the two issues are that "+" is part of the "Arith" group 
generic (?Methods, ?Arith) and that `+` (actually, members of the Ops 
group) for primitive types dispatches directly without doing method 
look-up. Personally I might

setClass("Character", contains="character")

Character <- function(...) new("Character", ...)

setMethod("Arith", c("Character", "Character"), function(e1, e2) {
     switch(.Generic,
            "+"=Character(paste(e1, e2, sep="")),
            stop("unhandled 'Arith' operator '", .Generic, "'"))
})

and then

 > Character(c("foo", "bar")) + Character("baz")
[1] "foobaz" "barbaz"

Some might point to

 > `%+%` <- function(e1, e2) paste(e1, e2, sep="")
 > "foo" %+% "bar"
[1] "foobar"

Martin