Skip to content

Instantly share code, notes, and snippets.

@emekoi
Last active August 3, 2016 21:58
Show Gist options
  • Save emekoi/a56617ef6dd4c623335bda3befaabb96 to your computer and use it in GitHub Desktop.
Save emekoi/a56617ef6dd4c623335bda3befaabb96 to your computer and use it in GitHub Desktop.
stacks, linked lists oh my
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!
-- 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
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