Skip to content

Instantly share code, notes, and snippets.

@mecampbellsoup
Created January 29, 2014 17:55
Show Gist options
  • Save mecampbellsoup/8693291 to your computer and use it in GitHub Desktop.
Save mecampbellsoup/8693291 to your computer and use it in GitHub Desktop.
Trivial Ruby implementation of Lisp, where ::cons creates the list, and ::car / ::cdr return the head and tail, respectively.
module Lisp
  def cons(x,y)
    -> (m) { m.call(x,y) }
  end

  def car(z)
    z.call(-> (p, q) { p })
  end

  def cdr(z)
    z.call(-> (p, q) { q })
  end
end
# Note: copy/paste the above into pry/irb, and then `include Lisp`

# list of 2 values
car(cons(1,5)) #=> 1
cdr(cons(1,5)) #=> 5
# list of 1 list and 1 value
car(car(cons(cons(5,2),1))) #=> 5
cdr(car(cons(cons(5,2),1))) #=> 2
cdr(cons(cons(5,2),1))      #=> 1
# list of 2 lists each with values
car(car(cons(cons(5,2),cons(3,4)))) #=> 5
cdr(car(cons(cons(5,2),cons(3,4)))) #=> 2
car(cdr(cons(cons(5,2),cons(3,4)))) #=> 3
cdr(cdr(cons(cons(5,2),cons(3,4)))) #=> 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment