Skip to content

Instantly share code, notes, and snippets.

@stefanoc
Created December 21, 2015 15:39
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 stefanoc/b0b91e2f34dff6f58c43 to your computer and use it in GitHub Desktop.
Save stefanoc/b0b91e2f34dff6f58c43 to your computer and use it in GitHub Desktop.
List
class List
attr_accessor :head, :tail
def initialize(head, tail)
self.head = head
self.tail = tail
freeze
end
def prepend(elem)
List.new(elem, self)
end
def append(elem)
if tail.nil?
List.new(head, list(elem))
else
List.new(head, tail.append(elem))
end
end
def inspect
"(#{head}, #{tail.inspect})"
end
end
def list(*elements)
if elements.size == 1
List.new(elements[0], nil)
else
List.new(elements[0], list(*elements[1..-1]))
end
end
l = list(1, 2, 3, 4)
l = l.prepend(0)
puts l.inspect
l = l.append(5)
puts l.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment