Are there ruby equivalents to the lisp car, cdr, and cons functions? For those unfamiliar with lisp, here's what I want from ruby:
[1,2,3].car => 1
[1,2,3].cdr => [2,3]
[2,3].cons(1) => [1,2,3]
(in lisp):
(car '(1 2 3)) => 1
(cdr '(1 2 3)) => (2 3)
(cons 1 '(2 3)) => (1 2 3)
Of course, as you know, these aren't too close to Lisp. The real ruby equivalent would be something like
[1, [2, [3, nil]]]
. You could always write a List class...or find one somewhere.Chapter 8 of Practical Ruby Projects is called Implementing Lisp in Ruby.
I'd recommend reading the Ruby API for
Array
. There are many methods and operators there that can do exactly what you need.http://www.ruby-doc.org/core/classes/Array.html
Semi-seriously, if you want CONS, CAR, and CDR in Ruby, you could do worse than
And then you can define your list procedures,
And then you might get the sum of the odd squares in the range 1 to 10:
Ruby arrays are not implemented as singly-linked lists, so it is not as useful to have car and cdr and stuff.
If you really wanted, you could do
No there isn't, but it is easy enough to write your own if needed.
This is how you'd implement lisp-like single-linked lists in ruby: