Multiple Return Values in Racket

In Racket, we can define functions that return multiple values using the values form. Here’s an example demonstrating this feature:

#lang racket

; This function returns 2 values
(define (vals)
  (values 3 7))

(define (main)
  ; Here we use the 2 different return values with multiple assignment
  (define-values (a b) (vals))
  (displayln a)
  (displayln b)

  ; If you only want a subset of the returned values,
  ; you can use the underscore '_' as a placeholder
  (define-values (_ c) (vals))
  (displayln c))

(main)

To run this program, save it in a file (e.g., multiple-return-values.rkt) and use the racket command:

$ racket multiple-return-values.rkt
3
7
7

In this example, we define a function vals that returns two values using the values form. In the main function, we demonstrate how to receive these multiple return values.

The define-values form is used to bind multiple values to variables. In the first example, we bind both returned values to a and b.

If you only want a subset of the returned values, you can use the underscore _ as a placeholder for values you don’t need. This is similar to the blank identifier in some other languages.

Racket’s multiple value return and define-values form provide a clean and efficient way to return and handle multiple values from a single function call.