Skip to content

Instantly share code, notes, and snippets.

@xoebus
Created April 21, 2012 15:53
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 xoebus/2437963 to your computer and use it in GitHub Desktop.
Save xoebus/2437963 to your computer and use it in GitHub Desktop.
A Ruby Version of Steve Losh's Lightning Talk at BACON 2012: Pulling Lists out of Thin Air
# Pulling List's out of Thin Air
# Ruby Implementation of Steve Losh's Lightning Talk at BACON 2012
def prepend item, list
->(h) {
return h ? item : list
}
end
def head list
list.call(true)
end
def tail list
list.call(false)
end
def get list, index
if index == 0
head(list)
else
get(tail(list), index - 1)
end
end
def length list
if list.nil?
0
else
1 + length(tail(list))
end
end
def append item, list
if list.nil?
prepend(item, list)
else
prepend(head(list), append(item, tail(list)))
end
end
def reverse list
if list.nil?
nil
else
append(head(list), reverse(tail(list)))
end
end
greeting = nil
greeting = append("Hello", greeting)
greeting = append("BACON", greeting)
greeting = append("I'm Chris", greeting)
puts "greeting.size: #{length(greeting)}"
puts "greeting[0]: #{get(greeting, 0)}"
puts "greeting[1]: #{get(greeting, 1)}"
puts "greeting.reverse[0]: #{get(reverse(greeting), 0)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment