Simply Scheme Exercises. Chapter 06 True and False.

Discussion of Scheme and Racket
Post Reply
korekaradesu
Posts: 1
Joined: Sun Apr 21, 2013 8:22 pm

Simply Scheme Exercises. Chapter 06 True and False.

Post by korekaradesu » Sun Apr 21, 2013 9:09 pm

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.

sylwester
Posts: 133
Joined: Mon Jul 11, 2011 2:53 pm

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

Post by sylwester » Wed Apr 24, 2013 12:41 am

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) :)
Last edited by sylwester on Wed Apr 24, 2013 9:36 am, edited 1 time in total.
I'm the author of two useless languages that uses BF as target machine.
Currently I'm planning a Scheme compiler :p

Kompottkin
Posts: 94
Joined: Mon Jul 21, 2008 7:26 am
Location: München, Germany
Contact:

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

Post by Kompottkin » Wed Apr 24, 2013 7:34 am

korekaradesu wrote:1. Any non false value is true in Scheme.
Yes. And empty? is non-false (it's not #f but a function).

saulgoode
Posts: 45
Joined: Tue Dec 14, 2010 1:39 am

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

Post by saulgoode » Wed Apr 24, 2013 4:09 pm

korekaradesu wrote:But in the interpreter, it returns the value of (empty? 3).
Your interpreter should return the value 3 for the cond expression.

Post Reply