user7120460
user7120460

Reputation:

Why this test with Rackunit does not work?

I am using Racket and Dr. Racket for educational purposes.

I am trying to understand the values built-in function.

When I call values with the following input I get this output:

> (values 'this 'and-this 'and-that)
'this
'and-this
'and-that

Why does this test fail?

#lang racket

(require rackunit racket/trace)

(check-equal? (values 'this 'and-this 'and-that) 'this 'and-this 'and-that)

Upvotes: 1

Views: 137

Answers (2)

Sylwester
Sylwester

Reputation: 48745

You can convert multiple values to a list and then compare it to expected values:

(define-syntax values->list
  (syntax-rules ()
    ((_ expr) 
     (call-with-values (lambda () expr) 
                       list))))

(check-equal? (values->list (values 'this 'and-this 'and-that))
              (list 'this 'and-this 'and-that))

values is very special. It ties with call-with-values. Practically it works pretty much the same as list and apply but without making cons being created in between. Thus its just an optimization. In an implementation using stack it would return values on the stack and call-with-values would just apply with the same frame it got from applying the thunk.

I do think Common Lisp version is more useful as it allows multiple value procedures to be used in single value situations with only the first value being used. In Scheme dialects you need to use call-with-values or a macro or procedure that uses it in order to handle multiple values, which is less flexible but perhaps can do other calls slightly more effiecent.

Upvotes: 1

Óscar López
Óscar López

Reputation: 236004

Because values is returning multiple values, and check-equal? can't handle that, it expects exactly two values to compare. For instance, this would work because we're dealing with only two values:

(check-equal? (values 42) 42)

Try a different approach, let's say we first unpack the multiple values and put them in a list:

(check-equal?
 (let-values ([(a b c) (values 'this 'and-this 'and-that)])
   (list a b c))
 '(this and-this and-that))

Upvotes: 1

Related Questions