Created
January 18, 2018 02:24
-
-
Save JoelQ/6225ba3f83b908d8e16ea16b2f2dd7af to your computer and use it in GitHub Desktop.
Linked-list (cons list) implementation in Ruby
This file contains 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 EmptyList | |
def prepend(value) | |
List.new(value, self) | |
end | |
def inspect | |
"()" | |
end | |
def map(&block) | |
self | |
end | |
def each(&block) | |
end | |
def first | |
nil | |
end | |
def rest | |
nil | |
end | |
end |
This file contains 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_reader :first, :rest | |
def initialize(first, rest) | |
@first = first | |
@rest = rest | |
end | |
def prepend(value) | |
List.new(value, self) | |
end | |
def map(&block) | |
List.new(block.call(first), rest.map(&block)) | |
end | |
def each(&block) | |
block.call(first) | |
rest.each(&block) | |
self | |
end | |
def inspect | |
"(#{first.inspect}, #{rest.inspect})" | |
end | |
def to_s | |
inspect | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment