What does it mean when a function is defined with two pairs of brackets

6

I have noticed a function defined as such:

 f[x_][y_] := expr;

How is the argument y in 2nd pair of brackets being used? What is the difference from defining a function this way:

 f[x_, y_] := expr;

spaceKnot

Posted 2013-12-31T03:19:34.317

Reputation: 363

1

It allows you to work with and pass around f[something] as a separate object. You could for example Map it easily. See for example this question and the two answers: one uses subvalues ("double bracket") and the other uses downvalues (a single bracket) to achieve the same thing. The downvalues version needs to create new symbol names with extra definitions for each instance of the structure it's generating. The subvalues version doesn't.

– Szabolcs – 2013-12-31T04:04:03.837

1

Related/duplicate: What is the distinction between DownValues, UpValues, SubValues, and OwnValues?

– rm -rf – 2013-12-31T04:27:23.943

Answers

8

It allows partial function application. Observe how function test1 defined this way can be called with the first argument, resulting in the return of another function of the remaining argument. Function test2 does not, and simply returns unevaluated since no match to its pattern occurs.

Clear[test1,test2]

test1[x_][y_]:=x^y
test2[x_,y_]:=x^y

test1[2][3]
(* 8 *)

test2[2,3]
(* 8 *)

test1[2]
(* test1[2] *)

%[3]
(* 8 *)

test2[2]
(* test2[2] *)

%[3]
(* test2[2][3] *)

ciao

Posted 2013-12-31T03:19:34.317

Reputation: 23 752

To state it explicitly, you can define something like test3 = test1[2], and then call test3 /@ Range[4] – Jason B. – 2015-11-17T12:11:47.703