Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Complexity of ELT Function in Common Lisp for Various Sequence Types

I am trying to get an understanding of how the ELT function works when it comes to different sequence types.

It seems obvious that when a list is passed to it, then the performance is of order O(n). Is it true to say that getting an element from a VECTORP sequence is of order O(1)? What about a string?

This does not seem to be specified on HyperSpec or Common Lisp The Language.

like image 604
MadPhysicist Avatar asked May 23 '18 17:05

MadPhysicist


People also ask

What does ELT do in Lisp?

Simplified Common Lisp reference - elt. ELT function accesses specified elements of sequences. The index is counted from zero. Accessing out-of-bounds indices signals condition, or causes crash and/or undefined behavior, depending on compilation safety mode.

What is a sequence in Lisp?

A sequence is a Lisp object that represents an ordered set of elements. There are two kinds of sequence in Emacs Lisp: lists and arrays. Lists are the most commonly-used sequences. A list can hold elements of any type, and its length can be easily changed by adding or removing elements.


1 Answers

Generally speaking, the ANSI CL standard does not specify implementation details - including performance issues such as this one. Another example is tail call elimination, mandated by Scheme but not CL. This does not mean, of course, that the authors of the standard were oblivious to performance (cf. "performance impact" section in every issue writeup).

That said, you can safely assume that elt is O(1) on vectors (including strings).

I don't think elt is used very often though - mostly because one usually knows whether a vector or a list is actually used. Using aref/char/nth serves as extra code documentation.

PS. The rationale for this dramatic difference between CL and Scheme is that Scheme's origin is in teaching: its users are new students who should learn computer programming as a methodology of expressing ideas about algorithms, thus they should have a relatively simple tool with clearly defined behavior. ANSI CL's history shows that the standard was a result of an effort of several existing vendors to come up with some common ground for better portability - to make competition more fair, so to speak. The audience are seasoned programmers who know the trade and can understand performance trade offs.

like image 192
sds Avatar answered Sep 18 '22 22:09

sds