Queue/Definition: Difference between revisions

Content deleted Content added
+ AutoHotkey contributed by Laszlo from ahk forums
Added R code
Line 1,166:
not fifo # empty
fifo.pop() -> raises IndexError when empty
 
=={{header|R}}==
===Simple functional implementation===
This simple implementation provides three functions that act on a variable in the global environment (user workspace) named ''l''. the push and pop functions display the new status of ''l'', but return NULL silently.
<lang R>
empty <- function() length(l) == 0
push <- function(x)
{
l <<- c(l, list(x))
print(l)
invisible()
}
pop <- function()
{
if(empty()) stop("can't pop from an empty list")
l[[1]] <<- NULL
print(l)
invisible()
}
l <- list()
empty()
# [1] TRUE
push(3)
# [[1]]
# [1] 3
push("abc")
# [[1]]
# [1] 3
# [[2]]
# [1] "abc"
push(matrix(1:6, nrow=2))
# [[1]]
# [1] 3
# [[2]]
# [1] "abc"
# [[3]]
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
empty()
# [1] FALSE
pop()
# [[1]]
# [1] 3
# [[2]]
# [1] "abc"
pop()
# [[1]]
# [1] 3
pop()
# list()
pop()
# Error in pop() : can't pop from an empty list
</lang>
 
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.)
 
===Object oriented implementation===
A better solution is to use the object oriented facility in the proto package. (R does have it's own native object oriented code, though the proto package is often nicer to use.)
 
<lang R>
library(proto)
 
fifo <- proto(expr = {
l <- list()
empty <- function(.) length(.$l) == 0
push <- function(., x)
{
.$l <- c(.$l, list(x))
print(.$l)
invisible()
}
pop <- function(.)
{
if(.$empty()) stop("can't pop from an empty list")
.$l[[1]] <- NULL
print(.$l)
invisible()
}
})
 
#The following code provides output that is the same as the previous example.
fifo$empty()
fifo$push(3)
fifo$push("abc")
fifo$push(matrix(1:6, nrow=2))
fifo$empty()
fifo$pop()
fifo$pop()
fifo$pop()
fifo$pop()
</lang>
 
 
=={{header|Ruby}}==