7
$\begingroup$

I want to define a function like

f[x_][y_][z_] := x + 2y + 3z

but anonymously. The ways to do this that I've discovered so far are

(1) define a normal function first, then curry it:

f = Function[{x,y,z}, x + 2y + 3z] // Curry[#,3]&

(2) define the function in λ-calculus style:

f = Function[x, Function[y, Function[z, x + 2y + 3z]]]

However, none of these look good. Is there a way to define an anonymous function f in its curried form directly? Something like

f = CurriedFunction[{x,y,z}, x + 2y + 3z]
$\endgroup$
0

2 Answers 2

6
$\begingroup$

I think I found a way to do it nicely:

f = x |-> y |-> z |-> x + 2 y + 3 z

It looks nicer in the front end:

enter image description here

$\endgroup$
1
$\begingroup$

How about this?

SetAttributes[CurriedFunction, HoldAll];
CurriedFunction[vars_, body_] := 
  If[VectorQ[vars] && Length[vars] > 0,
   Block[vars,
    Fold[Function[#2, #1] &, Function[Evaluate[vars[[-1]]], body], 
     Rest[Reverse[vars]]]
    ],
   Function[vars, body]
   ];

x = 7;
y = 8;
z = 9;
f = CurriedFunction[{x, y, z}, 1 + 1 + x + 2 y + 3 z]
f[x][y][z]

Function[x, Function[y, Function[z, 1 + 1 + x + 2 y + 3 z]]]

50

$\endgroup$
1
  • $\begingroup$ Thanks Henrik. If I want to define CurriedFunction, then I can simply do CurriedFunction[vars_, body_] := Curry[Function[Evaluate@vars, body], Length[vars]]; that's clear. I'm more looking for a builtin functionality. $\endgroup$
    – Roman
    Aug 26, 2019 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.