[plt-scheme] problem with example macro

From: Danny Yoo (dyoo at hkn.eecs.berkeley.edu)
Date: Wed Nov 22 10:56:57 EST 2006


On Wed, 22 Nov 2006, michael rice wrote:

> (define-syntax nth-value
>  (syntax-rules ()
>    ((nth-value n values-producing-form)
>     (call-with-values
>       (lambda () values-producing-form)
>       (lambda all-values
>         (list-ref all-values n))))))
>
> =================================
>
> Welcome to DrScheme, version 360.
> Language: Swindle.
>> (nth-value 3 '(a b c d e f))
> . list-ref: index 3 too large for list: ((a b c d e
> f))


Hi Michael,

You're running into something that doesn't really have to do with macros. 
NTH-VALUE gets the n'th value of the value-producing-form expression. 
But the expression you have:

     '(a b c d e f)

is a single value: a list.


We can return mutiple values out of a function by using the VALUES form. 
For example:

     (values '(hello world) '(this is a) 'test)

will send three values to whoever is requesting it.


Here's another example of multiple values:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require (lib "list.ss"))

(define empty-stack '())

(define (stack-push stack item)
   (cons item stack))

(define (stack-pop stack)
   (values (first stack) (rest stack)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


Here, STACK-POP is a function that returns two values: the element we're 
popping off, and the rest of the stack.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
> (let*-values ([(my-stack) (stack-push empty-stack 'hello)]
                 [(my-stack) (stack-push my-stack 'world)]
                 [(x my-stack) (stack-pop my-stack)]
                 [(y my-stack) (stack-pop my-stack)])
     (printf "x: ~a~n" x)
     (printf "y: ~a~n" y))
x: world
y: hello
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


Hope this helps!


Posted on the users mailing list.