Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Created Jan 18, 2018
Embed
What would you like to do?
Linked-list (cons list) implementation in Ruby
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
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