1
Is it true that this is an S-expression?
xyz

asks The Little Schemer. but how to test?


syntactically, i get how to test other statements like

> (atom? 'turkey)

and

> (list? '(atom))

not entirely sure how to test this...

> (list? '(atom turkey) or)

as it just returns...

or: bad syntax in: or

but anyway, knowing how to test for S-expressions is foxing me

so, as per usual, any illumination much appreciated

Will Ness
  • 70,110
  • 9
  • 98
  • 181
user3435279
  • 85
  • 1
  • 8

2 Answers2

2

An "S-expression" is built of atoms via several (possibly zero) cons applications:

(define (sexp? expr)
  (or
     ; several cases:
     (atom? expr)
     ; or
     (and (pair? expr)           ; a pair is built by a cons
          (sexp? (car expr))     ;  from a "car"
          (sexp? .........))     ;    and a "cdr"
          ))) 

This is practically in English. Nothing more to say about it (in code, I mean). Except, after defining the missing

(define (atom? x) 
  (not (pair? x)))

we see that (sexp? ...) can only return #t. This is the whole point to it: in Lisp, everything is an S-expression – either an atom, or a pair of S-expressions.

Will Ness
  • 70,110
  • 9
  • 98
  • 181
0

The previous answer is correct -- Scheme (and Lisp) are languages that are based on S-expressions. And the provided code is a great start.

But it's not quite correct that everything is an S-expression in those languages. In this case you have an expression that isn't syntactically correct, so the language chokes when it tries to read it in. In other words, it's not an S-expression.

I know it's frustrating, and honestly, not that great of an answer, but this is a great lesson in one of the Golden Rules of Computer Programming: Garbage In, Garbage Out. The fat is that you are going to get these kinds of errors simply because it isn't really feasible, when starting out programming, to test for every possible way that something isn't an S-expression without using the language itself.

Jeff P.
  • 91
  • 1
  • 1
  • 6
  • `(list? '(atom turkey) or)` is an S-expression too. It's when the REPL tries to evaluate it - i.e. when it treats it as a LISP code - that the problem arises. :) Calling `(sexp? '(list? '(atom turkey) or))` should return `#t`. – Will Ness Jul 11 '14 at 23:55