Page 1 of 1

Simply Scheme Exercises. Chapter 06 True and False.

PostPosted: Sun Apr 21, 2013 9:09 pm
by korekaradesu
Hey Schemers, new Scheme user here. Looking for enlightenment on an exercise I'm doing at the end of Simply Scheme chapter 06 True and False.

Boring exercise 6.1 has the following cond expression:

(cond (empty? 3)
(square 7)
(else 9))

In my head, this should return the value of (square 7). But in the interpreter, it returns the value of (empty? 3).
(Tested the return of (empty?) by changing the '3' to other atoms and lists).

Why is this?

What I understand:
1. Any non false value is true in Scheme.
2. The first statement is evaluated and if true the interpreter returns #t, what is specified or #unspecified dependent on context then exits the cond.

What I don't understand:
1. If the result of (empty? 3) is #f, wouldn't it evaluate the next cond argument?
2. If the interpreter evaluates (empty? 3), why doesn't it return #t in this case? (as when the expression is evaluated on its own?)

Using SCM with Slib and the libraries that come with the book (simply.scm functions.scm ttt.scm match.scm database.scm) loaded.

Re: Simply Scheme Exercises. Chapter 06 True and False.

PostPosted: Wed Apr 24, 2013 12:41 am
by sylwester
The predicate and the consequent need to be in a list.
Code: Select all
(cond ((empty? 3) (square 7))
      (else 9))


Scheme evaluates the first element of the list and if it's #t it will evaluate the rest of the list (implicit begin).

It's false that your code would return #f as it most definitely would return 3 since empty? is not #f. My corrected one on the other hand will return 9 since empty? is defined like this:
Code: Select all
(define (empty? x)
    (or (null? x)
         (and (string? x) (string=? x ""))))


Thus will return #t only on empty list and empty string. 3 is neither => #f. Try switching the 3 with '() or "" to get (square 7) :)

Re: Simply Scheme Exercises. Chapter 06 True and False.

PostPosted: Wed Apr 24, 2013 7:34 am
by Kompottkin
korekaradesu wrote:1. Any non false value is true in Scheme.


Yes. And empty? is non-false (it's not #f but a function).

Re: Simply Scheme Exercises. Chapter 06 True and False.

PostPosted: Wed Apr 24, 2013 4:09 pm
by saulgoode
korekaradesu wrote:But in the interpreter, it returns the value of (empty? 3).

Your interpreter should return the value 3 for the cond expression.