Jump to content

Queue/Definition: Difference between revisions

→‎{{header|R}}: alternate R solution (Scheme like)
(→‎{{header|R}}: alternate R solution (Scheme like))
Line 2,183:
 
The problem with this is that the functions aren't related to the FIFO object (the list ''l''), and they require the list to exist in the global environment. (This second problem is possible to get round by passing ''l'' into the function and then returning it, but that is extra work.)
 
===Alternate functional implementation===
 
<lang r># The usual Scheme way : build a function that takes commands as parameters (it's like message passing oriented programming)
queue <- function() {
v <- list()
f <- function(cmd, val=NULL) {
if(cmd == "push") {
v <<- c(v, val)
invisible()
} else if(cmd == "pop") {
if(length(v) == 0) {
stop("empty queue")
} else {
x <- v[[1]]
v[[1]] <<- NULL
x
}
} else if(cmd == "length") {
length(v)
} else if(cmd == "empty") {
length(v) == 0
} else {
stop("unknown command")
}
}
f
}
 
# Create two queues
a <- queue()
b <- queue()
a("push", 1)
a("push", 2)
b("push", 3)
a("push", 4)
b("push", 5)
 
a("pop")
# [1] 1
b("pop")
# [1] 3</lang>
 
===Object oriented implementation===
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.