有没有办法将所有可选参数传递给另一个函数?

时间:2018-10-01 18:24:02

标签: racket

我有一个函数A,它接受10个可选参数。 我有另一个函数B,它具有相同的10个可选参数。 有没有简单的方法可以将一个函数的可选参数传递给另一个函数?

1 个答案:

答案 0 :(得分:0)

口译员的解决方案

在解释器中,您可以简单地通过以下方式进行操作:

; 0. define your arguments list which the functions have in common
(define args-list '(1 2 3 4 5 6 7 8 9 10))

; 1. call the functions `your-function` -> your function name:
(eval `(your-function ,@args-list))

脚本解决方案

#lang racket

;; -------------------
;; prepare eval-call
;; -------------------

(define-namespace-anchor a)
(define ns (namespace-anchor->namespace a)) 
; this captures namespace for `eval` call in a script

;; -------------------
;; define macro for function call using an argument list
;; -------------------

(define-syntax-rule (fcall fun args)
    (eval `(fun ,@args) ns))

;; -------------------
;; define two silly example functions with 10 optional arguments
;; -------------------

(define (add-10 [a 0] [b 0] [c 0] [d 0] [e 0] [f 0] [g 0] [h 0] [i 0] [j 0])
  (+ a b c d e f g h i j))

(define (mult-10 [a 1] [b 1] [c 1] [d 1] [e 1] [f 1] [g 1] [h 1] [i 1] [j 1])
  (* a b c d e f g h i j))

;; -------------------
;; define two example arguments lists
;; -------------------

(define args-list '(1 2 3 4 5 6 7 8 9 10))
(define args-list1 '(5 5 5))

;; -------------------
;; call the two different functions using the same argument lists
;; -------------------

(fcall add-10 args-list)   ;; => 55
(fcall mult-10 args-list)  ;; => 3628800

(fcall add-10 args-list1)  ;; => 15
(fcall mult-10 args-list1) ;; => 125

;; in the interpreter, you can also directly call:
;(eval `(add-10 ,@args-list))
;(eval `(mult-10 ,@args-list))
;
;(eval `(add-10 ,@args-list1))
;(eval `(mult-10 ,@args-list1))
;; no namespace argument needed in interpreter, when calling `eval`

使用可选关键字参数列表进行脚本编写的解决方案

; now, let's do it for keyword arguments lists 
; with optional keyword arguments

;; -------------------
;; define two silly example functions with 10 optional keyword arguments
;; -------------------

(define (add-it-10 #:a [a 0] #:b [b 0] #:c [c 0] #:d [d 0] #:e [e 0] 
                   #:f [f 0] #:g [g 0] #:h [h 0] #:i [i 0] #:j [j 0])
  (+ a b c d e f g h i j))

(define (mult-it-10 #:a [a 1] #:b [b 1] #:c [c 1] #:d [d 1] #:e [e 1] 
                    #:f [f 1] #:g [g 1] #:h [h 1] #:i [i 1] #:j [j 1])
  (* a b c d e f g h i j))

;; -------------------
;; let's define an example arguments list with keywords
;; -------------------

(define args-list2 '(#:a 1 #:b 2 #:c 3 #:d 4 #:g 10))

;; -------------------
;; call the two different functions using the same argument list
;; -------------------

(fcall add-it-10 args-list2)    ;; => 20
(fcall mult-it-10 args-list2)   ;; => 240


; ;also thinkable definition of `fcall`:
;(define-syntax-rule (fcall fun args)
;    (apply fun args))
; note, this definition doesn't work with keyword argument lists!
; that is why the combination of eval and splicing of argument list 
; is in my view the best