我有一个函数,它接受一个可变长度的参数列表。并依赖 它的长度,我必须调用另一个函数,但具有不同长度的参数。你看到下面的功能:
(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条款可能更长。它工作但绝对不合适。
有没有更好的方法来填写这个功能?
答案 0 :(得分: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))))
但是,既然你实际上并没有使用除了获得参数计数之外的参数,那看起来很可疑。你想做什么?
答案 1 :(得分: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))))))
当然打败人类编译器