Hello,
I could not find a stack implementation in Mata, so I put together a quick one (see code below).
The code works but because the matrix initializer J(r,c,z) does not permit r==0 or c==0, I had to resort to an ugly hack (the "initialized" variable) to simulate an empty stack.
Also, I could not figure out how to shrink or grow a vector without losing content (other than by first copying the contents to another vector and then copying them back).
Is there a better way of implementing this? Other ways to improve the code?
Cheers,
I could not find a stack implementation in Mata, so I put together a quick one (see code below).
The code works but because the matrix initializer J(r,c,z) does not permit r==0 or c==0, I had to resort to an ugly hack (the "initialized" variable) to simulate an empty stack.
Also, I could not figure out how to shrink or grow a vector without losing content (other than by first copying the contents to another vector and then copying them back).
Is there a better way of implementing this? Other ways to improve the code?
Cheers,
Code:
set matastrict on //all vars must be pre-declared
mata:
version 13.2
mata clear
//Class vdecStack provides a basic stack data structure
class vdecStack {
private:
string colvector _arr
string colvector _c
real scalar initialized
public:
void new() //constructor
void push()
string scalar pop()
void print()
}
void vdecStack::new()
{
initialized = 0
}
void vdecStack::push(string scalar item) {
if (initialized == 1 ) {
_c = _arr
_arr = J(1,cols(_arr)+1,"")
_arr[1..cols(_c)] = _c
_arr[cols(_arr)] = item
}
else {
initialized = 1
_arr =J(1,1,"")
_arr[1] = item
}
}
string scalar vdecStack::pop() {
if (initialized == 0 ) {
_error("nothing to pop")
return
}
string scalar item
if (cols(_arr)==1 ) {
item = _arr[1]
_arr[1] = ""
initialized = 0
return(item)
}
item = _arr[cols(_arr)]
_arr =_arr[1,cols(_arr)-1]
return(item)
}
void vdecStack::print()
{
if (initialized == 0 ) {
printf("[]\n")
return
}
real scalar i
printf("[")
for (i=1; i< cols(_arr); i ++) {
printf("%s,",_arr[i])
}
printf("%s]\n",_arr[i])
}
void numTest() {
class vdecStack scalar s
s = vdecStack()
s.print()
printf("pushing 1\n")
s.push("1")
s.print()
printf("pushing 2\n")
s.push("2")
s.print()
printf("%s popped\n", s.pop())
s.print()
printf("%s popped\n", s.pop())
s.print()
printf("try to pop an empty stack\n")
s.pop()
}
numTest()
end

Comment