2

我有一个函数,它接受一个可变长度的参数列表。并且取决于它的长度,我必须调用另一个函数,但参数长度不同。您会看到以下功能:

  (define (set-contents . args)
   (define columns-length (length args))
        (cond
          ((= columns-length 1) 
           (send output-list set (empty-list rows-length) (get-nth-item columns-as-list 0)))
          ((= columns-length 2) 
           (send output-list set (empty-list rows-length) (get-nth-item columns-as-list 0) (get-nth-item columns-as-list 1)))
          ((= columns-length 3) 
           (send output-list set (empty-list rows-length) (get-nth-item columns-as-list 0) (get-nth-item columns-as-list 1) (get-nth-item columns-as-list 2)))
          ((= columns-length 4) 
           (send output-list set (empty-list rows-length) (get-nth-item columns-as-list 0) (get-nth-item columns-as-list 1) (get-nth-item columns-as-list 2) (get-nth-item columns-as-list 3)))

这个 cond 子句还可以更长。它正在工作,但绝对不合适。

有没有更好的方法来填补这个功能?

4

2 回答 2

2

嗯,直接翻译思路如下:

(define (set-contents . args)
  (send/apply output-list set (empty-list rows-length)
                              (for/list ((i (length args)))
                                (get-nth-item columns-as-list i))))

但是,由于除了获取参数计数之外,您实际上并没有使用参数,这看起来很可疑。你想做什么?

于 2013-08-13T05:51:39.020 回答
0

使用申请?

(define (set-contents . args)
  (define columns-length (length args))
  (apply send (append (list output-list set '()) 
                      (take column-length columns-as-list))))

(define (take num lst)
  (cond ((< num 1) '())
        ((null? lst) (error "Cannot TAKE from the empty list")
        (else (cons (car lst) (take (- num 1) (cdr lst))))))

当然胜过成为人类编译器

于 2013-08-13T13:20:18.800 回答