Help an oop newbie

Hi folks, I am trying to learn a bit of how to extend R using object oriented programming. I set myself a little task to extend numerics so that if the value equals 7 "little bunny foo foo" will be printed. In other cases, the actual value will be printed. My code is

new_nursery_Song <- function(x = double()){
  stopifnot(is.double(x))
  structure(x,class = c("nursery_Song","numeric"))
}

print.nursery_Song <- function(x){
  if (x == 7)
    print("little bunny foo foo")
  else
    print(x)
}
print(new_nursery_Song(7))
print(new_nursery_Song(3))

which gives

[1] "little bunny foo foo"
Error: C stack usage  15927136 is too close to the limit

(My guess is that print() is being called recursively rather than going to the generic print(), but it's just a guess.)

Any help will be greatly appreciated, including telling me that I'm thinking about this entirely in the wrong way. By way of background,

  1. It's been a long time since I've done any object oriented programming.
  2. I've never done oop in R (which you've probably already guessed).

I have read through the relevant parts of both Hands on Programming with R (Grolemund) and Advanced R (Wickham). Both quite helpful.

This is correct, when x is not 7 it will endlessly try to call print.nursery_Song, to fix have it use the default print for numeric, like so

new_nursery_Song <- function(x = double()){
  stopifnot(is.double(x))
  structure(x,class = c("nursery_Song","numeric"))
}

print.nursery_Song <- function(x){
  if (x == 7)
"little bunny foo foo"
  else
    print(as.numeric(x))
}
print(new_nursery_Song(7))
print(new_nursery_Song(3))

Thanks @nirgrahamuk, that solves my problem. Since I'm mostly doing this to learn, any more guidance or pointers on how to think about inheritance?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.