## Example of string class using OOP ## similar to string class in ruby require(OOP) defineClass("String") String$defineFields(string = "character") ## New. String$defineMethod("initialize", function(val) { set.string(as.character(val)) }) ## simpler interface string = function(x) String$new(x) ## length String$defineMethod("length",function() { return(nchar(string)) }) ## summary String$defineMethod("summary",function() { return(table(strsplit(string,""))) }) ## show . show() is for S4 methods, These are not. Still ## need a print method defined below String$defineMethod("show", function() cat(string,"\n")) ## slice String$defineMethod("slice",function(index) { splitUpString = unlist(strsplit(string,"")) tmp = splitUpString[index] return(String$new(paste(tmp,sep="",collapse=""))) }) ### Concatanation String$defineMethod("concat",function(y,sep="") { return(String$new(paste(string,as.character(y),sep=sep))) }) ## repeat String$defineMethod("rept",function(n,sep="") { return(String$new(paste(rep(string,n),sep=sep,collapse=""))) }) ## split on a regexp ## returns a vector of characters! String$defineMethod("split",function(by="") { unlist(strsplit(string,by)) }) ## modify the value in place String$defineMethod("upcase",function() { set.string(toupper(string)) }) ## return upcased value as string object String$defineMethod("upcase.it",function() { String$new(toupper(string)) }) String$defineMethod("downcase",function() { String$new(tolower(string)) }) ## S4 Methods for syntactical sugar setMethod("print","String", function(x,...) x$show()) setMethod("[","String",function(x,i,j,...,drop) x$slice(i)) setMethod("+","String",function(e1,e2) e1$concat(e2)) setMethod("*","String",function(e1,e2) e1$rept(e2)) setMethod("/","String",function(e1,e2) e1$split(e2)) ### S3 style methods would look like this ### print.String = function(self) self$show() ### "[.String" = function(self,index) self$slice(index) ### "+.String" = function(self,x) self$concat(x) ### "*.String" = function(self,n) self$rept(n) ### "/.String" = function(self,y) self$split(y) defineClass("Sentence", extends = "String") Sentence$defineMethod("punctuate",function() { ## add a period, and capitalize the first letter chars = split("") chars[1] = toupper(chars[1]) if(chars[(length)(chars)] != ".") chars[(length)(chars)+1] = "." set.string(paste(chars,sep="",collapse="")) })