Skip to content

Instantly share code, notes, and snippets.

@yxhuvud
Created September 12, 2019 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yxhuvud/c7e520fd2f6928205441c9739e38fb78 to your computer and use it in GitHub Desktop.
Save yxhuvud/c7e520fd2f6928205441c9739e38fb78 to your computer and use it in GitHub Desktop.
module LinkedList(T)
macro included
include Enumerable(T)
property _next, _prev : T | Nil
end
def append(node : T)
node.next = @_next
node.prev = self
@_next = node
end
def prepend(node : T)
node.next = self
node.prev = @_next
@_prev = node
end
def detach
if prev = @_prev
prev.next = @_next
end
if _next = @_next
_next.prev = @_prev
end
@_next = @_prev = nil
self
end
def each
current = self
yield current
while current = current._next
yield current
end
nil
end
def head?
@_prev.nil?
end
def tail?
@_next.nil?
end
def next : T | Nil
_next
end
def prev : T | Nil
_prev
end
protected def next=(value : T | Nil)
@_next = value
end
protected def prev=(value : T | Nil)
@_prev = value
end
end
class Test
property value : Int32
include LinkedList(self)
def initialize(@value)
end
end
x = Test.new(5)
y = Test.new(6)
x.append(y)
p x.sum &.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment