Search code examples
schemetuplesracketconsmultiple-value

Difference between multiple values and plain tuples in Racket?


What is the difference between values and list or cons in Racket or Scheme? When is it better to use one over the other? For example, what would be the disadvantage if quotient/remainder returns (cons _ _) rather than (values _ _)?


Solution

  • Back in 2002 George Caswell asked that question in comp.lang.scheme. The ensuing thread is long, but has many insights. The discussion reveals that opinions are divided.

    https://groups.google.com/d/msg/comp.lang.scheme/ruhDvI9utVc/786ztruIUNYJ

    My answer back then:

    >    What are the motivations behind Scheme's multiple return values feature?
    > Is it meant to reflect the difference in intent, or is there a
    > runtime-practical reason?
    
    I imagine the reason being this.
    
    Let's say that need f is called by g. g needs several values from f.
    Without multiple value return, f packs the values in a list (or vector),
    which is passed to g. g then immediately unpacks the list.
    
    With multple values, the values are just pushed on the stack. Thus no
    packing and unpacking is done.
    
    Whether this should be called an optimization hack or not, is up to you.
    
    --
    Jens Axel Søgaard
    
    We don't need no side-effecting         We don't need no allocation
    We don't need no flow control           We don't need no special-nodes
    No global variables for execution       No dark bit-flipping for debugging
    Hey! did you leave the args alone?      Hey! did you leave those bits alone?
    (Chorus)                  -- "Another Glitch in the Call", a la Pink Floyd