如何在 Racket 中对任意数量的参数使用柯里化?

How do I use currying with an arbitrary number of arguments in Racket?

假设我想用柯里化语法定义一个类似 format 的函数。我将如何处理可以传递的附加参数?例如,我希望能够执行以下操作:

(((format "~a ~a") 5) 9)

是的,这很棘手。问题是 format 应该如何知道它拥有所有参数。我猜你希望格式能够解析它的输出字符串并确定它需要多少个参数,然后在收到正确数量的参数时触发。你最终会自己卷起来。像这样的东西(注意:未经测试的代码):

#lang racket

;; given a format-string, return a curried function that
;; accepts the format-string's arguments one at a time
(define (curried-format fmt-str)
  (define num-args-expected (count-format-string-args fmt-str))
  (define (so-far->waiter so-far)
    (lambda (arg)
      (define new-args (cons arg so-far))
      ;; do we have all of the args?
      (if (= (length new-args) num-args-expected)
          ;; yay! call format:
          (apply format fmt-str (reverse new-args))
          ;; nope: wait for some more:
          (so-far->waiter new-args))))
  (so-far->waiter '()))