Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Created January 18, 2018 02:24
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 JoelQ/6225ba3f83b908d8e16ea16b2f2dd7af to your computer and use it in GitHub Desktop.
Save JoelQ/6225ba3f83b908d8e16ea16b2f2dd7af to your computer and use it in GitHub Desktop.
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