Skip to content

Instantly share code, notes, and snippets.

@jeffreybaird
Created December 4, 2015 20:59
Show Gist options
  • Save jeffreybaird/32e51cc18944b7c504d7 to your computer and use it in GitHub Desktop.
Save jeffreybaird/32e51cc18944b7c504d7 to your computer and use it in GitHub Desktop.
A linked list implementation
class LinkedList
attr_reader :tail
def initialize(head=nil, tail=NullList.new())
raise ArgumentError unless tail.is_a?(LinkedList) || tail.is_a?(NullList)
@head = head.is_a?(Head) ? head : Head.new(head)
@tail = tail
end
def head
@head
end
def to_a
[head.value,tail.to_a]
end
def to_s
to_a.to_s
end
def flatten
to_a.flatten
end
def end?
false
end
def unshift(new_item)
return self.class.new(Head.new(new_item), self.tail) if head.nil?
self.class.new(Head.new(new_item), self)
end
def push(new_item)
new_item = Head.new(new_item) if !new_item.is_a?(Head)
return self.class.new(new_item, self.tail) if head.nil?
if tail.is_a?(NullList)
return self.class.new(head, self.class.new(new_item,self.tail))
end
self.class.new(head,tail.push(new_item))
end
def map(acc=LinkedList.new,&block)
a = yield(head)
new_acc = acc.push(a)
return new_acc if tail.end?
tail.map(new_acc,&block)
end
end
class Head
attr_reader :value
def initialize(value)
@value = value
end
def +(val)
return self if value.nil?
self.class.new(value + val)
end
def nil?
value.nil?
end
end
class NullList
def to_a
[nil]
end
def end?
true
end
def method_missing(*args, &block)
nil
end
def push(new_item)
self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment