Created
December 21, 2015 15:39
-
-
Save stefanoc/b0b91e2f34dff6f58c43 to your computer and use it in GitHub Desktop.
List
This file contains hidden or 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 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