Create a list containing T as one item

I ran into a problem when I'm not sure if everything is okay with me, which I have learned so far on Lisp.

In principle, the task is trivial: create a list containing only one element - the literal T

My first approach:

 '(t) 

It is right? In principle, he estimates

 (T) 

which seems right. Since the T character is evaluated on its own, this should do the job. But then it made me think ... If I write

 '(s) 

I get:

 (S) 

It looks about the same, but should be evaluated differently. So I thought about

 (list t) 

which also leads to:

 (T) 

If I compare characters using eq , they are equal:

 (eq (car (list t)) (car '(t))) 

And also, if I compare both values ​​with T directly, everything is fine:

 (eq (car (list t)) t) (eq (car '(t)) t) 

So, to shorten the long story: '(t) does the job, doesn't it?

+7
lisp common-lisp
source share
1 answer

I do not think you fully understand the assessment.

Now let's look at the Lisp code. This means the source code of a programming language. Not s-expressions:

 '(t) 

The above:

 (quote (t)) 

If we evaluate it, Lisp sees a special QUOTE statement. QUOTE prevents the evaluation of a closed form and returns it.

Thus, the result is (T) . T never rated. (T) never rated. (T) is a constant literal.

If you write '(s) or '(sin) or any other character, it does not matter. It is always a constant literal list of one character.

Code again:

 (list t) 

This app features. When evaluating:

  • Lisp sees the list with LIST as a function.

  • he computes the arguments. T is evaluated on its own.

  • it calls LIST with argument T

  • the LIST function returns a new list: (T) .

What's 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 returns a new list each time.

Both lists contain the same character: T

Thus, the difference is reduced to constant data in comparison with the data created by the function.

+8
source share

All Articles