lae*_*tao 2 generics stack r data-structures
我已经写了堆"类"具有以下功能:add
,push
,pop
,size
,isEmpty
,clear
(多一些).
我想在R中使用这个"类"作为泛型,所以我可以在我的脚本中创建多个堆栈实例.我该怎么做呢?
(我在引号中有类,因为我的堆栈函数是用不同的脚本编写的(不一定是类本身的定义)
提前致谢
list <- ""
cursor = 0
#Initializes stack to empty
stack <- function(){
list <- c()
cursor = -1
assign("list",list,.GlobalEnv)
assign("cursor",cursor,.GlobalEnv)
}
#Where item is a item to be added to generic list
push <- function(item){
if(size(list) == 0){
add(item, -1)
}else{
add(item, 0)
}
assign("list",list,.GlobalEnv)
}
Run Code Online (Sandbox Code Playgroud)
这是一个更简单的堆栈实现@GSee引用版本,它避免使用R中可用的任何正式的面向对象系统.简化从R中的所有函数都是闭包这一事实开始,函数调用期间创建的函数绑定到为该呼叫创建的环境.
new_stack <- function() {
stack <- vector()
push <- function(x) stack <<- c(stack, x)
pop <- function() {
tmp<-tail(stack, 1)
stack<<-stack[-length(stack)]
return(tmp)
}
structure(list(pop=pop, push=push), class='stack')
}
x <- new_stack()
x$push(1:3)
x$pop()
# [1] 3
x$pop()
# [1] 2
Run Code Online (Sandbox Code Playgroud)
这是一个S4实现,用于比较.
setClass('Stack',
representation(list='list', cursor='numeric'), # type defs
prototype(list=list(), cursor=NA_real_)) # default values
setGeneric('push', function(obj, ...) standardGeneric('push'))
setMethod('push', signature(obj='Stack'),
function(obj, x) {
obj@list <- c(x, obj@list)
obj
})
setGeneric('pop', function(obj, ...) standardGeneric('pop'))
setMethod('pop', signature(obj='Stack'),
function(obj) {
obj@cursor <- obj@list[[1]]
obj@list <- obj@list[-1]
obj
}
)
x <- new('Stack')
# cursor is empty to start
x@cursor
#[1] NA
# add items
x <- push(x, 1)
x <- push(x, 2)
# pop them (move next item to cursor, remove from list)
x <- pop(x)
x@cursor
# [1] 2
x <- pop(x)
x@cursor
# [1] 1
Run Code Online (Sandbox Code Playgroud)