Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Currying for functions with n (3 or more) arguments?

For functions with three or more arguments, how does currying work?

I searched over SO and Google. Concrete examples given in e.g. What is 'Currying'? ; https://en.wikipedia.org/wiki/Currying are about binary functions f (x, y).

In that case, g = curry f takes one parameter and produces a unary function (f x).

My question is:

How do we extend this consistently to a n-parameter function, e.g. f3 (x,y,z)? (f3: X->Y->Z->U)

If the curry operation is treated as a higher order function, it can't directly apply to f3, because curry expects a function of type (X,Y) -> Z, and the argument of f3 is a triple, not a pair. The same issue arises with a function fn that takes an n-tuple.

One solution might be to equate (x,y,z) and (x,(y,z)), then curry seems to apply. Then curry f3 = (f3 x) is of type (Y,Z) -> U. But is this how curry is supposed to be?

like image 206
thor Avatar asked Nov 05 '15 18:11

thor


Video Answer


1 Answers

If the curry operation is treated as a higher order function, it can't directly apply to f3, because curry expects a function of type (X,Y) -> Z, and the argument of f3 is a triple, not a pair. The same issue arises with a function fn that takes an n-tuple.

There are aspects of your question that include much of the strong typing of Haskell that aren't present in most Lisps. For instance, an easy n-ary curry could be defined as:

(defun curry (function first-argument)
  (lambda (&rest args)
    (apply function first-argument args)))

CL-USER> (let ((f (curry (curry (lambda (x y z)
                                  (* x (+ y z)))
                                2)
                         3)))
           (mapcar f '(1 2 3 4 5)))
; (8 10 12 14 16)
like image 63
Joshua Taylor Avatar answered Nov 08 '22 18:11

Joshua Taylor