Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use (values ...) (define-values ...) in Scheme

Tags:

scheme

I have read documentation for functions such as values and define-values that return and consume multiple values. I understand what they do. It's not clear to me when you would want to use such a thing.

When would it be bad/impossible to build a single list of values and consume that single list of values instead?

like image 547
Mark Bolusmjak Avatar asked Nov 06 '09 05:11

Mark Bolusmjak


People also ask

How do you define a constant in a Scheme?

Just define the value at the toplevel like a regular variable and then don't change it. To help you remember, you can adopt a convention for naming these kinds of constants - I've seen books where toplevel variables are defined with *stars* around their name.

How do you check if a number is even in Scheme?

If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator % like this num % 2 == 0 . If a number divided by 2 leaves a remainder of 1, then the number is odd. You can check for this using num % 2 == 1 .

How do you use if statements in schemes?

In Scheme, there's no need for both an if statement and an if-like ternary expression operator, because if "statements" are expressions. Note that even though every expression returns a value, not all values are used--you can ignore the return value of an if expression.

Why is begin needed in Scheme?

begin is normally used when there is some side-effect. "If you omit the begin, then you simply could not write this expression". You can actually write that expression using lambda: (+ x ((lambda (x) y) (set! y (+ y 1))) z) .


2 Answers

define-values is a convenience that lets you directly bind variables to the results of a expression. It saves you some typing as you don't have to explicitly unpack a list. I don't think there are situations where it is bad or impossible to build a single list of values. In fact, that will be more portable than define-values.

like image 145
Vijay Mathew Avatar answered Sep 22 '22 10:09

Vijay Mathew


Here is my original post on the topic; it is copied below.

In this thread in comp.lang.scheme the means to return multiple values are discussed. There are seemingly 3 solutions in R6RS:

(import (rnrs))

; let-values + values
(define (foo1)
  (values 1 2 3))

(let-values (((a b c) (foo1)))
  (display (list a b c))
  (newline))

; cps
(define (foo2 k)
  (k 1 2 3))

(foo2 (lambda (a b c) 
        (display (list a b c))
        (newline)))

; list
(define (foo3)
  (list 1 2 3))
(let ((result (foo3)))
  (display result)
  (newline))

Per Aziz and Aaron’s point; you should use the approach that communicates the most information to the reader.

like image 44
grettke Avatar answered Sep 23 '22 10:09

grettke