I have come across a problem where I'm not sure whether I got everything right I learned so far on Lisp.
Basically the task is trivial: Create a list that contains only a single item - the T
literal.
My first approach was:
'(t)
Is this correct? Basically, it evaluates to
(T)
which seems to be correct. As the symbol T
evaluates to itself, this should do the job. But then it got me thinking… If I write
'(s)
I get:
(S)
This looks pretty much the same, but should evaluate in a different way. So I thought about
(list t)
which also results in:
(T)
If I compare the symbols using eq
they are equal:
(eq (car (list t)) (car '(t)))
And also if I I compare both values to T
directly, everything is fine:
(eq (car (list t)) t)
(eq (car '(t)) t)
So, to cut a long story short: '(t)
does the job, doesn't it?
Using Collections. singletonList() Method [ Immutable List ] This is simplest and recommended method to create immutable List with single element inside it. The list created with this method is immutable as well, so you are sure that there will not be any more elements in list, at any condition.
You don't want to mutate the list in place (eg by using . pop() ). To check that the list contains only one element, you could use a couple of try , except statements to check that (1) you can access the first element, and (2) you can't access a second element. Really, the most Pythonic way is to just use len .
Python list represents a mathematical concept of a finite sequence. Values of a list are called items or elements of the list. A list can contain the same value multiple times. Each occurrence is considered a distinct item.
I don't think you understand evaluation fully.
We now look at Lisp code. That means source code of a programming language. Not s-expressions:
'(t)
Above is the same as:
(quote (t))
If we evaluate it, Lisp sees the QUOTE
special operator. QUOTE
prevents evaluation of the enclosed form and returns it.
Thus the result is (T)
. T
never gets evaluated. (T)
never gets evaluated. (T)
is a constant literal list.
If you write '(s)
or '(sin)
or whatever other symbol, it does not matter. It is always a constant literal list of one symbol.
Code again:
(list t)
That's a function application. When evaluated:
Lisp sees a list with LIST
as a function.
it evaluates the arguments. T
is evaluated to itself.
it calls LIST
with the argument T
.
the function LIST
returns a fresh list: (T)
.
What is the difference between
(defun foo ()
'(t))
and
(defun bar ()
(list t))
?
FOO
returns a constant literal list, embedded in the code.
BAR
calls LIST
at runtime and each time it returns a fresh list.
Both lists contain the same symbol: T
.
So the difference boils down to constant data vs. data created by a function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With