Is there a way to turn a list into values. So something like the magic function in this example:
(define-values (name age) (magic '("Bob" 25)))
Is there a way to turn a list into values. So something like the magic function in this example:
(define-values (name age) (magic '("Bob" 25)))
You can do this with pattern matching.
#lang racket
(require racket/match)
(define (magic lst)
(match lst
[(list a b) (values a b)]
[else lst]))
Welcome to DrRacket, version 8.11.1 [cs].
Language: racket, with debugging; memory limit: 4096 MB.
(define-values (name age) (magic '("Bob" 25)))
name
"Bob"
age
25
I think what you really are looking for is pattern matching. If you use #lang racket
, you can do:
(match-define (list name age) '("Bob" 25))
But if you really want to use the multiple values approach (which is inefficient compared to the pattern matching approach), you could do:
(define-values (name age) (apply values '("Bob" 25)))
Disclaimer: Blatant self promotion ahead
Using the implementation of SRFI-210: Procedures and Syntax for Multiple Values, from my extra-srfi-libs
collection:
Welcome to Racket v8.11.1 [cs].
> (require srfi/210)
> (define-values (name age) (list-values '("Bob" 25)))
> name
"Bob"
> age
25
(Though I agree with everyone else that using pattern matching is likely a better option for this trivial case.)
A third possibility is
#lang racket
(define-values (name age) (apply values'("Bob" 25)))
name ; ==> "Bob"
age ; ==> 25