for循环中的多个绑定

vpo*_*yev 3 for-loop racket

因此,Racket(6.5)文档说您可以同时绑定多个ID:

(for ([(i j) #hash(("a" . 1) ("b" . 20))])
    (display (list i j)))
Run Code Online (Sandbox Code Playgroud)

Bu-u-ut我无法找出/找到如何使用手动构造的数据执行此操作的示例:

(define a '(1 2 3 4 5))
(define b '(10 20 30 40 50))
(for ([(i j) (map list a b)])
    (display (list i j)))
Run Code Online (Sandbox Code Playgroud)

与...爆炸

result arity mismatch;
 expected number of values not received
  expected: 2
  received: 1
  from: 
  in: local-binding form
  values...:
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Tox*_*ris 5

在此示例中,您可以使用单独的子句进行绑定, i并且j:

(for ([i (list 1 2 3 4 5)]
      [j (list 10 20 30 40 50)])
  (display (list i j)))
Run Code Online (Sandbox Code Playgroud)

更一般地,您可以使用in-parallel从多个单个值序列创建多个值的单个序列:

(for ([(i j) (in-parallel (list 1 2 3 4 5)
                          (list 10 20 30 40 50))])
    (display (list i j)))
Run Code Online (Sandbox Code Playgroud)

这两种解决方案打印(1 10)(2 20)(3 30)(4 40)(5 50).


soe*_*ard 5

这个

(for ([(i j) #hash(("a" . 1) ("b" . 20))])
    (display (list i j)))
Run Code Online (Sandbox Code Playgroud)

是的缩写

(for ([(i j) (in-hash #hash(("a" . 1) ("b" . 20)))])
    (display (list i j)))
Run Code Online (Sandbox Code Playgroud)

现在一次in-hash返回两个值,因此(i j) 将绑定到这两个值.

另一方面,这个:

(for ([(i j) (map list a b)])
    (display (list i j)))
Run Code Online (Sandbox Code Playgroud)

是的缩写

(for ([(i j) (in-list (map list a b))])
    (display (list i j)))
Run Code Online (Sandbox Code Playgroud)

并且in-list将一次返回一个元素(在您的示例中,元素是列表).由于有两个名称(i j) 而不仅仅是一个,因此会发出错误信号.

按照Toxaris的建议in-parallel.

UPDATE

以下帮助程序make-values-sequence显示如何创建自定义序列,该序列重复生成多个值.

#lang racket

(define (make-values-sequence xss)
  ; xss is a list of (list x ...)
  (make-do-sequence (? ()
                      (values (? (xss) (apply values (first xss))) ;  pos->element
                              rest                                 ;  next-position
                              xss                                  ;  initial pos
                              (? (xss) (not (empty? xss)))         ;  continue-with-pos?
                              #f                                   ;  not used
                              #f))))                               ;  not used]


(for/list ([(i j) (make-values-sequence '((1 2) (4 5) (5 6)))])
  (+ i j))
Run Code Online (Sandbox Code Playgroud)

输出:

'(3 9 11)
Run Code Online (Sandbox Code Playgroud)