Why it is `(cons 1 (cons 2 (cons 3 nil)))` and not `(cons 3 (cons 2 (cons 1 nil)))` for [1,2,3]

data structuresfunctional programminglistscheme

Is there any special reason that to construct list in Scheme you use

(cons 1 (cons 2 (cons 3 nil)))

instead of

(cons 3 (cons 2 (cons 1 nil)))

? While the first seems more obvious because it reads in the right order, the second is the one which actually reduces in the right order. Also, it seems more natural to construct a list starting with nil and adding elements to it, not the opposite. I've also found the latter has properties such as being very curry friendly: (cons 1) nicely becomes a function that appends 1 to a list.

Best Answer

How do you propose the head be reached in this reversed list? If not using mutable structures the reversed list would only be performant if you made the head linear time and tail constant. But now you've got the exact same structure as before except you're calling the head the tail and vice versa.

the structure is the way it is because regardless of which side you declare to be the front or the back, that particular form is the only known one with constant time readahead and constant time insert without mutation or doing amortization trickery.

you're getting hung up on the terms thinking one side could be head or tail but those terms don't matter, the part that counts is the structure.

Related Topic