Are There Ruby Equivalents to Car, Cdr, and Cons

Are there ruby equivalents to car, cdr, and cons?

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

[1,2,3][0]      => 1
[1,2,3].first => 1
[1,2,3][1..-1] => [2,3]
[1] + [2,3] => [1,2,3]

Is it still inadvisable to define constructors and selectors as cons, car, and cdr?

Quite often they will be. For instance imagine some debugger which is trying to print a backtrace in a useful way. It's going to want to map between the procedure objects sitting in the backtrace and their names. And that map is either going to point at the 'wrong' name, or it's going to point at all the names and you then have to know which one you actually used.

Here's an example in Racket:

> (object-name cons)
'cons
> (define make-thingy cons)
> (object-name make-thingy)
'cons

Extension methods equivalents for CAR and CDR in .Net's Linq/IEnumerable

For CDR you can use Enumerable.Skip(1) like:

var cdrResultQuery = someIEnumerable.Skip(1);

Consider following example:

IEnumerable<int> someIEnumerable = new List<int> {1, 2, 3, 4, 5};
var cdrResultQuery = someIEnumerable.Skip(1);
foreach (var i in cdrResultQuery)
{
Console.WriteLine(i);
}

and you will get:

2
3
4
5

Do you have a mnemonic for remembering the meaning of car and cdr?

Of the two words car and cdr, car is the one I've heard first.

Memory representation of values in Lisp

"Lisp" is a family of languages, not a single language. Many languages in the family (e.g., Common Lisp) don't specify the internal representations, but rather the contract that the structures and functions have to preserve. In the case of cons, it's roughly the equations:

(car (cons x y)) == x
(cdr (cons x y)) == y

and the requirement that cons returns a new object each time it's called. In some Lisps, cons cells are immutable, and so the requirement that a new object is returned isn't present.

Of course, there are actually implementations, and they do actually have to store things, and it's not unreasonable to ask how they do that. In general, it's probably best to think of a cons cell as a structure big enough to hold two pointers, and probably some information holding its type (so that it can be recognized as a cons cell). The pointers used by the implementaiton might be tagged, though, so that if, e.g., the first three bits are some special values, the "pointer" can be recognized as the encoding of some primitive value.

The important part here is that you usually don't need to know the underlying representation on the machine, and that in the cases that you do (e.g., if you're writing code to interface with another language (e.g., C)), then the answers that you're looking for are going to be specific to each implementation.



Related Topics



Leave a reply



Submit