0

I'm writing some guile code that gets a list of a set length, and I need to define a variable for every element in the list. Currently, I have to do something like this:

(define (foo l)
  (let ((e-1 (car l))
        (e-2 (cadr l))
        (e-2 (caddr l))
        ; ...
        (e-n (list-ref (- n 1)
                       l)))
    (compute)))

This gets super tedious. Is there anyway I can do something like this instead?

(define (foo l)
  (symbol-def e-1 e-2 e-3 e-4 e-n l)
  (compute))

Edit: Made question more guile-specific.

charmlessCoin
  • 754
  • 3
  • 13
  • possible duplicate of [What is scheme's equivalent of tuple unpacking?](http://stackoverflow.com/questions/4220515/what-is-schemes-equivalent-of-tuple-unpacking) – amalloy Jan 24 '14 at 02:02

3 Answers3

0

Guile-specific, I've found the ice-9 match module, which has the following form:

(match lst
    ((pattern) expr))

Example:

(use-modules (ice-9 match))

(let ((l '(test foo bar)))
  (match l
    ((head second third)
     second)))

; returns `foo`
charmlessCoin
  • 754
  • 3
  • 13
0

Using multiple values is one way to bind the elements of a list of known length to variables:

;;; Using SRFI-8 receive syntax
(use-modules (ice-9 receive))
(define (foo l)
  (receive (e-1 e-2 e-3 e-4) (apply values l)
    (format #t "~S~%~S~%~S~%~S~%" e-1 e-2 e-3 e-4)))
(foo '(1 2 3 4))

;;; Using SRFI-11 let-values syntax
(use-modules (srfi srfi-11))
(define (foo2 l)
  (let-values (((e-1 e-2 e-3 e-4) (apply values l)))
    (format #t "~S~%~S~%~S~%~S~%" e-1 e-2 e-3 e-4)))
(foo2 '(a b c d))

;;; Using R5RS call-with-values
(define (foo3 l)
  (call-with-values
    (lambda () (apply values l))
    (lambda (e-1 e-2 e-3 e-4)
      (format #t "~S~%~S~%~S~%~S~%" e-1 e-2 e-3 e-4))))
Shawn
  • 47,241
  • 3
  • 26
  • 60
0

Another thing worth mentioning is define-values

(define (bar l)
  (define-values (a b c d) (apply values l))
  (compute a b c d))
Stefan
  • 271
  • 1
  • 4