What's illegal about my function?

Discussion of Scheme and Racket
Post Reply
flagrant2
Posts: 1
Joined: Sun May 03, 2015 11:42 pm

What's illegal about my function?

Post by flagrant2 » Sun May 03, 2015 11:51 pm

Hi everyone. I'm new to scheme and functional programming in general, so I apologize if this kind of question gets asked a lot. I've tried every conceivable search phrase and lots of modifications, consulted numerous books and tutorials, but the error message just isn't descriptive. I'm afraid I'm fundamentally misunderstanding the language or something.

I'm attempting to write a function that prints each entry of a list on its own line using by re-cursing on the tail. Here's what I have:

Code: Select all

(define print-list
  (lambda (l)
    (if (null? l)
        (display "done\n")
        (  (display (car l))  (newline)  (print-list (cdr l)) ))))

(print-list '(1 2 3 4 5) )
Here's how I'm running it and what I get:

Code: Select all

john@home:~/code/lisp$ tinyscheme helloworld.scm
1
2
3
4
5
done
Error: (helloworld.scm : 8) illegal function 
Errors encountered reading helloworld.scm
john@home:~/code/lisp$
The thing runs as I expected, but then shows me the error message and exits. What have I done wrong?

Thanks very much in advance!

Goheeca
Posts: 271
Joined: Thu May 10, 2012 12:54 pm
Contact:

Re: What's illegal about my function?

Post by Goheeca » Tue May 05, 2015 2:18 pm

If you used another implementation of scheme things wouldn't happen so good. You are trying to use a block of code, but you can't just use surrounding parentheses:

Code: Select all

((expr1)
 (expr2)
 (expr3))
the first member of a list (expr1) is evaluated and used as an function, thus for a block of code there is an function begin:

Code: Select all

(begin (expr1)
       (expr2)
       (expr3))
Solution for your little problem is:

Code: Select all

(define print-list
  (lambda (l)
    (if (null? l)
      (display "done\n")
      (begin
        (display (car l))
        (newline)
        (print-list (cdr l))))))
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.

Post Reply