Is it possible to implement auto-currying to the Lisp-family languages?

前端 未结 6 2039
夕颜
夕颜 2020-12-31 06:15

That is, when you call a function with >1 arity with only one argument, it should, instead of displaying an error, curry that argument and return the resulting function with

6条回答
  •  Happy的楠姐
    2020-12-31 06:54

    In Scheme it's possible to curry a function using the curry procedure:

    (define (add x y)
      (+ x y))
    
    (add 1 2)           ; non-curried procedure call
    (curry add)         ; curried procedure, expects two arguments
    ((curry add) 1)     ; curried procedure, expects one argument
    (((curry add) 1) 2) ; curried procedure call
    

    From Racket's documentation:

    [curry] returns a procedure that is a curried version of proc. When the resulting procedure is first applied, unless it is given the maximum number of arguments that it can accept, the result is a procedure to accept additional arguments.

    You could easily implement a macro which automatically uses curry when defining new procedures, something like this:

    (define-syntax define-curried
        (syntax-rules ()
          ((_ (f . a) body ...)
           (define f (curry (lambda a (begin body ...)))))))
    

    Now the following definition of add will be curried:

    (define-curried (add a b)
      (+ a b))
    
    add
    > #
    
    (add 1)
    > #
    
    ((add 1) 2)
    > 3
    
    (add 1 2)
    > 3
    

提交回复
热议问题