Last active
August 3, 2016 21:58
-
-
Save emekoi/a56617ef6dd4c623335bda3befaabb96 to your computer and use it in GitHub Desktop.
stacks, linked lists oh my
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class fifo | |
MAX = 256*256 | |
new: (@maxSize = MAX) => | |
@stack = {} | |
@top = 0 | |
kill: => | |
@stack = nil | |
@top = nil | |
isEmpty: => | |
return @top < 1 | |
isFull: => | |
return @top >= @maxSize | |
peek: => | |
@stack[@top] | |
push: (...) => | |
for v in *{...} | |
if @isFull() | |
error "stack full" | |
os.exit! | |
else | |
@top += 1 | |
table.insert @stack,1,v | |
pop: (n = 1)=> | |
t = {} | |
while n > 0 | |
if not @isEmpty! | |
v = table.remove @stack,@top | |
@top-=1 | |
table.insert t,v | |
n -= 1 | |
else | |
error "stack empty" | |
n = 0 | |
os.exit! | |
table.unpack t | |
vm = fifo! | |
with vm | |
\push "value 1","value 2","value 3" | |
for k,v in ipairs .stack | |
print k | |
print \pop 2 | |
print \peek! | |
print \pop! | |
\kill! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- map function | |
map = (f, a, ...) -> | |
t = {} | |
for _ in *a | |
_i = _index_0 | |
t[_i] = f(_,...) | |
return t | |
-- fold functions | |
fold_a = (f, a, ...) -> | |
t = 0 | |
for _ in *a | |
t += f(_,...) | |
return t | |
fold_s = (f, a, ...) -> | |
t = 0 | |
for _ in *a | |
t += f(_,...) | |
return t |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class lifo | |
MAX = 256*256 | |
new: (@maxSize = MAX) => | |
@stack = {} | |
@top = 0 | |
kill: => | |
@stack = nil | |
@top = nil | |
isEmpty: => | |
return @top < 1 | |
isFull: => | |
return @top >= @maxSize | |
push: (v) => | |
if @isFull() | |
error "stack full" | |
os.exit! | |
else | |
@top += 1 | |
@stack[@top] = v | |
pop: => | |
if @isEmpty() | |
error "stack empty" | |
os.exit! | |
else | |
v = table.remove @stack,1 | |
@top-=1 | |
return v | |
vm = Stack! | |
with vm | |
\push "value 1" | |
\push "value 2" | |
\push "value 3" | |
for k,v in ipairs .stack | |
print k | |
print \pop! | |
for k,v in ipairs .stack | |
print k | |
print \pop! | |
for k,v in ipairs .stack | |
print k | |
print \pop! | |
for k,v in ipairs .stack | |
print k | |
\kill! | |
{:VM} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment