Currying: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 14: Line 14:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F addN(n)
<syntaxhighlight lang="11l">F addN(n)
F adder(x)
F adder(x)
R x + @=n
R x + @=n
Line 22: Line 22:
V add3 = addN(3)
V add3 = addN(3)
print(add2(7))
print(add2(7))
print(add3(7))</lang>
print(add3(7))</syntaxhighlight>


{{out}}
{{out}}
Line 34: Line 34:


Support package spec:
Support package spec:
<lang ada>generic
<syntaxhighlight lang="ada">generic
type Argument_1 (<>) is limited private;
type Argument_1 (<>) is limited private;
type Argument_2 (<>) is limited private;
type Argument_2 (<>) is limited private;
Line 63: Line 63:
end Apply_1;
end Apply_1;


end Curry_3;</lang>
end Curry_3;</syntaxhighlight>


Support package body:
Support package body:
<lang ada>package body Curry_3 is
<syntaxhighlight lang="ada">package body Curry_3 is


package body Apply_1 is
package body Apply_1 is
Line 83: Line 83:
end Apply_1;
end Apply_1;


end Curry_3;</lang>
end Curry_3;</syntaxhighlight>


Currying a function:
Currying a function:
<lang ada>with Curry_3, Ada.Text_IO;
<syntaxhighlight lang="ada">with Curry_3, Ada.Text_IO;


procedure Curry_Test is
procedure Curry_Test is
Line 112: Line 112:
Ada.Text_IO.Put_Line ("Five plus seven plus three is" & Integer'Image (Result));
Ada.Text_IO.Put_Line ("Five plus seven plus three is" & Integer'Image (Result));


end Curry_Test;</lang>
end Curry_Test;</syntaxhighlight>


Output:
Output:
Line 119: Line 119:
=={{header|Aime}}==
=={{header|Aime}}==
Curry a function printing an integer, on a given number of characters, with commas inserted every given number of digits, with a given number of digits, in a given base:
Curry a function printing an integer, on a given number of characters, with commas inserted every given number of digits, with a given number of digits, in a given base:
<lang aime>ri(list l)
<syntaxhighlight lang="aime">ri(list l)
{
{
l[0] = apply.apply(l[0]);
l[0] = apply.apply(l[0]);
Line 132: Line 132:
0;
0;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre> 000,040,000,000</pre>
<pre> 000,040,000,000</pre>
Line 138: Line 138:
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
In 1968 [[wp:Charles H. Lindsey|C.H. Lindsey]] proposed for '''partial parametrisation''' for ALGOL 68, this is implemented as an extension in [[wp:ALGOL 68G]].
In 1968 [[wp:Charles H. Lindsey|C.H. Lindsey]] proposed for '''partial parametrisation''' for ALGOL 68, this is implemented as an extension in [[wp:ALGOL 68G]].
<lang algol68># Raising a function to a power #
<syntaxhighlight lang="algol68"># Raising a function to a power #


MODE FUN = PROC (REAL) REAL;
MODE FUN = PROC (REAL) REAL;
Line 147: Line 147:


REAL x = read real;
REAL x = read real;
print ((new line, sin (3 * x), 3 * sin (x) - 4 * (sin ** 3) (x)))</lang>
print ((new line, sin (3 * x), 3 * sin (x) - 4 * (sin ** 3) (x)))</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
Line 153: Line 153:
The nearest thing to a first-class function in AppleScript is a 'script' in which a 'handler' (with some default or vanilla name like 'call' or 'lambda') is embedded. First class use of an ordinary 2nd class 'handler' function requires 'lifting' it into an enclosing script – a process which can be abstracted to a general mReturn function.
The nearest thing to a first-class function in AppleScript is a 'script' in which a 'handler' (with some default or vanilla name like 'call' or 'lambda') is embedded. First class use of an ordinary 2nd class 'handler' function requires 'lifting' it into an enclosing script – a process which can be abstracted to a general mReturn function.


<lang AppleScript>-- curry :: (Script|Handler) -> Script
<syntaxhighlight lang="applescript">-- curry :: (Script|Handler) -> Script
on curry(f)
on curry(f)
script
script
Line 250: Line 250:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<pre>{«script», «script», 5, {7, 14, 21, 28, 35, 42, 49, 56, 63, 70}}</pre>
<pre>{«script», «script», 5, {7, 14, 21, 28, 35, 42, 49, 56, 63, 70}}</pre>
Line 258: Line 258:


Adapted from [[Currying#J|J]].
Adapted from [[Currying#J|J]].
<lang bqn>Plus3 ← 3⊸+
<syntaxhighlight lang="bqn">Plus3 ← 3⊸+
Plus3_1 ← +⟜3
Plus3_1 ← +⟜3


•Show Plus3 1
•Show Plus3 1
•Show Plus3_1 1</lang>
•Show Plus3_1 1</syntaxhighlight>
<lang>4
<syntaxhighlight lang="text">4
4</lang>
4</syntaxhighlight>






=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include<stdarg.h>
#include<stdarg.h>
#include<stdio.h>
#include<stdio.h>
Line 301: Line 301:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 313: Line 313:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
This shows how to create syntactically natural currying functions in [[C sharp|C#]].
This shows how to create syntactically natural currying functions in [[C sharp|C#]].
<lang csharp>public delegate int Plus(int y);
<syntaxhighlight lang="csharp">public delegate int Plus(int y);
public delegate Plus CurriedPlus(int x);
public delegate Plus CurriedPlus(int x);
public static CurriedPlus plus =
public static CurriedPlus plus =
Line 321: Line 321:
int sum = plus(3)(4); // sum = 7
int sum = plus(3)(4); // sum = 7
int sum2= plus(2)(plus(3)(4)) // sum2 = 9
int sum2= plus(2)(plus(3)(4)) // sum2 = 9
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 328: Line 328:
=={{header|Ceylon}}==
=={{header|Ceylon}}==
{{trans|Groovy}}
{{trans|Groovy}}
<lang ceylon>shared void run() {
<syntaxhighlight lang="ceylon">shared void run() {
function divide(Integer x, Integer y) => x / y;
function divide(Integer x, Integer y) => x / y;
Line 337: Line 337:
a third is ``partsOf120(3)``
a third is ``partsOf120(3)``
and a quarter is ``partsOf120(4)``");
and a quarter is ``partsOf120(4)``");
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(def plus-a-hundred (partial + 100))
<syntaxhighlight lang="clojure">(def plus-a-hundred (partial + 100))
(assert (=
(assert (=
(plus-a-hundred 1)
(plus-a-hundred 1)
101))
101))
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun curry (function &rest args-1)
<syntaxhighlight lang="lisp">(defun curry (function &rest args-1)
(lambda (&rest args-2)
(lambda (&rest args-2)
(apply function (append args-1 args-2))))
(apply function (append args-1 args-2))))
</syntaxhighlight>
</lang>


Usage:
Usage:
<lang lisp>
<syntaxhighlight lang="lisp">
(funcall (curry #'+ 10) 10)
(funcall (curry #'+ 10) 10)


20
20
</syntaxhighlight>
</lang>


=={{header|Crystal}}==
=={{header|Crystal}}==
Crystal allows currying procs with either <code>Proc#partial</code> or by manually creating closures:
Crystal allows currying procs with either <code>Proc#partial</code> or by manually creating closures:


<lang ruby>add_things = ->(x1 : Int32, x2 : Int32, x3 : Int32) { x1 + x2 + x3 }
<syntaxhighlight lang="ruby">add_things = ->(x1 : Int32, x2 : Int32, x3 : Int32) { x1 + x2 + x3 }
add_curried = add_things.partial(2, 3)
add_curried = add_things.partial(2, 3)
add_curried.call(4) #=> 9
add_curried.call(4) #=> 9
Line 372: Line 372:
end
end
add13 = add_two_things(3).call(10)
add13 = add_two_things(3).call(10)
add13.call(5) #=> 18</lang>
add13.call(5) #=> 18</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.stdio, std.functional;
import std.stdio, std.functional;


Line 385: Line 385:
writeln("Add 2 to 3: ", add(2, 3));
writeln("Add 2 to 3: ", add(2, 3));
writeln("Add 2 to 3 (curried): ", add2(3));
writeln("Add 2 to 3 (curried): ", add2(3));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Add 2 to 3: 5
<pre>Add 2 to 3: 5
Line 393: Line 393:
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
{{Trans|C#}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Currying;
program Currying;


Line 420: Line 420:
readln;
readln;
end.
end.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 428: Line 428:
=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
[[EchoLisp]] has native support for curry, which is implemented thru closures, as shown in [[CommonLisp]] .
[[EchoLisp]] has native support for curry, which is implemented thru closures, as shown in [[CommonLisp]] .
<lang>
<syntaxhighlight lang="text">
;;
;;
;; curry functional definition
;; curry functional definition
Line 448: Line 448:
(curry * 2 3 (+ 2 2))
(curry * 2 3 (+ 2 2))
→ (λ _#:g1004 (#apply-curry #* (2 3 4) _#:g1004))
→ (λ _#:g1004 (#apply-curry #* (2 3 4) _#:g1004))
</syntaxhighlight>
</lang>


=={{header|Eero}}==
=={{header|Eero}}==
<lang objc>#import <stdio.h>
<syntaxhighlight lang="objc">#import <stdio.h>


int main()
int main()
Line 465: Line 465:


return 0
return 0
</syntaxhighlight>
</lang>
Alternative implementation (there are a few ways to express blocks/lambdas):
Alternative implementation (there are a few ways to express blocks/lambdas):
<lang objc>#import <stdio.h>
<syntaxhighlight lang="objc">#import <stdio.h>


int main()
int main()
Line 479: Line 479:


return 0
return 0
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
Line 498: Line 498:
There are three solutions provided for this problem. The simple version is using anonymous functions as other examples of other languages do. The second solution corresponds to the definition of currying. It takes a function of a arity ''n'' and applies a given argument, returning then a function of arity ''n-1''. The solution provided uses metaprogramming facilities to create the new function. Finally, the third solution is a generalization that allows to curry any number of parameters and in a given order.
There are three solutions provided for this problem. The simple version is using anonymous functions as other examples of other languages do. The second solution corresponds to the definition of currying. It takes a function of a arity ''n'' and applies a given argument, returning then a function of arity ''n-1''. The solution provided uses metaprogramming facilities to create the new function. Finally, the third solution is a generalization that allows to curry any number of parameters and in a given order.


<lang erlang>
<syntaxhighlight lang="erlang">
-module(currying).
-module(currying).


Line 561: Line 561:
erlang:error(badarg)
erlang:error(badarg)
end.
end.
</syntaxhighlight>
</lang>




Line 601: Line 601:
F# is largely based on ML and has a built-in natural method of defining functions that are curried:
F# is largely based on ML and has a built-in natural method of defining functions that are curried:


<lang fsharp>let addN n = (+) n</lang>
<syntaxhighlight lang="fsharp">let addN n = (+) n</syntaxhighlight>


<lang fsharp>> let add2 = addN 2;;
<syntaxhighlight lang="fsharp">> let add2 = addN 2;;


val add2 : (int -> int)
val add2 : (int -> int)
Line 610: Line 610:
val it : (int -> int) = <fun:addN@1>
val it : (int -> int) = <fun:addN@1>
> add2 7;;
> add2 7;;
val it : int = 9</lang>
val it : int = 9</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>IN: scratchpad 2 [ 3 + ] curry
<syntaxhighlight lang="factor">IN: scratchpad 2 [ 3 + ] curry


--- Data stack:
--- Data stack:
Line 620: Line 620:


--- Data stack:
--- Data stack:
5</lang>
5</syntaxhighlight>
Currying doesn't need to be an atomic operation. <tt>compose</tt> lets you combine quotations.
Currying doesn't need to be an atomic operation. <tt>compose</tt> lets you combine quotations.
<lang factor>IN: scratchpad [ 3 4 ] [ 5 + ] compose
<syntaxhighlight lang="factor">IN: scratchpad [ 3 4 ] [ 5 + ] compose


--- Data stack:
--- Data stack:
Line 630: Line 630:
--- Data stack:
--- Data stack:
3
3
9</lang>
9</syntaxhighlight>


You can even treat quotations as sequences.
You can even treat quotations as sequences.
<lang factor>IN: scratchpad { 1 2 3 4 5 } [ 1 + ] { 2 / } append map
<syntaxhighlight lang="factor">IN: scratchpad { 1 2 3 4 5 } [ 1 + ] { 2 / } append map


--- Data stack:
--- Data stack:
{ 1 1+1/2 2 2+1/2 3 }</lang>
{ 1 1+1/2 2 2+1/2 3 }</syntaxhighlight>


Finally, fried quotations are often clearer than using <tt>curry</tt> and <tt>compose</tt>. Use <tt>_</tt> to take objects from the stack and slot them into the quotation.
Finally, fried quotations are often clearer than using <tt>curry</tt> and <tt>compose</tt>. Use <tt>_</tt> to take objects from the stack and slot them into the quotation.
<lang factor>USE: fry
<syntaxhighlight lang="factor">USE: fry
IN: scratchpad 2 3 '[ _ _ + ]
IN: scratchpad 2 3 '[ _ _ + ]


--- Data stack:
--- Data stack:
[ 2 3 + ]</lang>
[ 2 3 + ]</syntaxhighlight>


Use <tt>@</tt> to insert the contents of a quotation into another quotation.
Use <tt>@</tt> to insert the contents of a quotation into another quotation.
<lang factor>IN: scratchpad { 1 2 3 4 5 } [ 1 + ] '[ 2 + @ ] map
<syntaxhighlight lang="factor">IN: scratchpad { 1 2 3 4 5 } [ 1 + ] '[ 2 + @ ] map


--- Data stack:
--- Data stack:
{ 4 5 6 7 8 }</lang>
{ 4 5 6 7 8 }</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
{{trans|Common Lisp}}
{{trans|Common Lisp}}
<lang forth>: curry ( x xt1 -- xt2 )
<syntaxhighlight lang="forth">: curry ( x xt1 -- xt2 )
swap 2>r :noname r> postpone literal r> compile, postpone ; ;
swap 2>r :noname r> postpone literal r> compile, postpone ; ;


5 ' + curry constant +5
5 ' + curry constant +5
5 +5 execute .
5 +5 execute .
7 +5 execute .</lang>
7 +5 execute .</syntaxhighlight>


{{out}}
{{out}}
Line 665: Line 665:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
FreeBASIC is not a functional language and does not support either currying or nested functions/lambdas which are typically used by otherwise imperative languages to implement the former. The nearest I could get to currying using the features which the language does support is the following:
FreeBASIC is not a functional language and does not support either currying or nested functions/lambdas which are typically used by otherwise imperative languages to implement the former. The nearest I could get to currying using the features which the language does support is the following:
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Type CurriedAdd
Type CurriedAdd
Line 682: Line 682:
Print "3 + 4 ="; add(3).add(4)
Print "3 + 4 ="; add(3).add(4)
Print "2 + 6 ="; add(2).add(6)
Print "2 + 6 ="; add(2).add(6)
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 704: Line 704:
[http://golang.org/ref/spec#Method_values Method values] were added
[http://golang.org/ref/spec#Method_values Method values] were added
in [http://golang.org/doc/go1.1#method_values Go 1.1].
in [http://golang.org/doc/go1.1#method_values Go 1.1].
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 740: Line 740:
fmt.Println("2 + 4 =", fn2(a, 4))
fmt.Println("2 + 4 =", fn2(a, 4))
fmt.Println("3 + 5 =", fn2(Foo(3), 5))
fmt.Println("3 + 5 =", fn2(Foo(3), 5))
}</lang>
}</syntaxhighlight>
[http://play.golang.org/p/0YL9YTe-9V Run on the Go Playground.]
[http://play.golang.org/p/0YL9YTe-9V Run on the Go Playground.]


Line 748: Line 748:


Example:
Example:
<lang groovy>def divide = { Number x, Number y ->
<syntaxhighlight lang="groovy">def divide = { Number x, Number y ->
x / y
x / y
}
}
Line 754: Line 754:
def partsOf120 = divide.curry(120)
def partsOf120 = divide.curry(120)


println "120: half: ${partsOf120(2)}, third: ${partsOf120(3)}, quarter: ${partsOf120(4)}"</lang>
println "120: half: ${partsOf120(2)}, third: ${partsOf120(3)}, quarter: ${partsOf120(4)}"</syntaxhighlight>


Results:
Results:
Line 763: Line 763:


Example (using the same "divide()" closure as before):
Example (using the same "divide()" closure as before):
<lang groovy>def half = divide.rcurry(2)
<syntaxhighlight lang="groovy">def half = divide.rcurry(2)
def third = divide.rcurry(3)
def third = divide.rcurry(3)
def quarter = divide.rcurry(4)
def quarter = divide.rcurry(4)


println "30: half: ${half(30)}; third: ${third(30)}, quarter: ${quarter(30)}"</lang>
println "30: half: ${half(30)}; third: ${third(30)}, quarter: ${quarter(30)}"</syntaxhighlight>


Results:
Results:
Line 776: Line 776:


=={{header|Haskell}}==
=={{header|Haskell}}==
Likewise in Haskell, function type signatures show the currying-based structure of functions (note: "<lang haskell>\ -></lang>" is Haskell's syntax for anonymous functions, in which the sign <lang haskell>\</lang> has been chosen for its resemblance to the Greek letter λ (lambda); it is followed by a list of space-separated arguments, and the arrow <lang haskell>-></lang> separates the arguments list from the function body)
Likewise in Haskell, function type signatures show the currying-based structure of functions (note: "<syntaxhighlight lang="haskell">\ -></syntaxhighlight>" is Haskell's syntax for anonymous functions, in which the sign <syntaxhighlight lang="haskell">\</syntaxhighlight> has been chosen for its resemblance to the Greek letter λ (lambda); it is followed by a list of space-separated arguments, and the arrow <syntaxhighlight lang="haskell">-></syntaxhighlight> separates the arguments list from the function body)
Prelude> let plus = \x y -> x + y
Prelude> let plus = \x y -> x + y
Line 792: Line 792:
8
8


In fact, the Haskell definition <lang haskell>\x y -> x + y</lang> is merely [[wp:syntactic sugar|syntactic sugar]] for <lang haskell>\x -> \y -> x + y</lang>, which has exactly the same type signature:
In fact, the Haskell definition <syntaxhighlight lang="haskell">\x y -> x + y</syntaxhighlight> is merely [[wp:syntactic sugar|syntactic sugar]] for <syntaxhighlight lang="haskell">\x -> \y -> x + y</syntaxhighlight>, which has exactly the same type signature:


Prelude> let nested_plus = \x -> \y -> x + y
Prelude> let nested_plus = \x -> \y -> x + y
Line 799: Line 799:


=={{header|Hy}}==
=={{header|Hy}}==
<lang hy>(defn addN [n]
<syntaxhighlight lang="hy">(defn addN [n]
(fn [x]
(fn [x]
(+ x n)))</lang>
(+ x n)))</syntaxhighlight>
<lang hy>=> (setv add2 (addN 2))
<syntaxhighlight lang="hy">=> (setv add2 (addN 2))
=> (add2 7)
=> (add2 7)
9
9


=> ((addN 3) 4)
=> ((addN 3) 4)
7</lang>
7</syntaxhighlight>


==Icon and {{header|Unicon}}==
==Icon and {{header|Unicon}}==
Line 814: Line 814:
used.
used.


<lang unicon>procedure main(A)
<syntaxhighlight lang="unicon">procedure main(A)
add2 := addN(2)
add2 := addN(2)
write("add2(7) = ",add2(7))
write("add2(7) = ",add2(7))
Line 826: Line 826:
procedure makeProc(A)
procedure makeProc(A)
return (@A[1], A[1])
return (@A[1], A[1])
end</lang>
end</syntaxhighlight>


{{Out}}
{{Out}}
Line 838: Line 838:
=={{header|Io}}==
=={{header|Io}}==
A general currying function written in the [[Io]] programming language:
A general currying function written in the [[Io]] programming language:
<lang io>curry := method(fn,
<syntaxhighlight lang="io">curry := method(fn,
a := call evalArgs slice(1)
a := call evalArgs slice(1)
block(
block(
Line 849: Line 849:
increment := curry( method(a,b,a+b), 1 )
increment := curry( method(a,b,a+b), 1 )
increment call(5)
increment call(5)
// result => 6</lang>
// result => 6</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==


'''Solution''':Use <tt>&</tt> (bond). This primitive conjunction accepts two arguments: a function (verb) and an object (noun) and binds the object to the function, deriving a new function.
'''Solution''':Use <tt>&</tt> (bond). This primitive conjunction accepts two arguments: a function (verb) and an object (noun) and binds the object to the function, deriving a new function.
'''Example''':<lang j> threePlus=: 3&+
'''Example''':<syntaxhighlight lang="j"> threePlus=: 3&+
threePlus 7
threePlus 7
10
10
Line 860: Line 860:
halve 20
halve 20
10
10
someParabola =: _2 3 1 &p. NB. x^2 + 3x - 2</lang>
someParabola =: _2 3 1 &p. NB. x^2 + 3x - 2</syntaxhighlight>


'''Note''': The final example (<tt>someParabola</tt>) shows the single currying primitive (&) combined with J's array oriented nature, permits partial application of a function of any number of arguments.
'''Note''': The final example (<tt>someParabola</tt>) shows the single currying primitive (&) combined with J's array oriented nature, permits partial application of a function of any number of arguments.
Line 866: Line 866:
'''Note''': J's adverbs and conjunctions (such as <code>&</code>) will curry themselves when necessary. Thus, for example:
'''Note''': J's adverbs and conjunctions (such as <code>&</code>) will curry themselves when necessary. Thus, for example:


<lang J> with2=: &2
<syntaxhighlight lang="j"> with2=: &2
+with2 3
+with2 3
5</lang>
5</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java5> public class Currier<ARG1, ARG2, RET> {
<syntaxhighlight lang="java5"> public class Currier<ARG1, ARG2, RET> {
public interface CurriableFunctor<ARG1, ARG2, RET> {
public interface CurriableFunctor<ARG1, ARG2, RET> {
RET evaluate(ARG1 arg1, ARG2 arg2);
RET evaluate(ARG1 arg1, ARG2 arg2);
Line 908: Line 908:
System.out.println(add5.evaluate(new Integer(2)));
System.out.println(add5.evaluate(new Integer(2)));
}
}
}</lang>
}</syntaxhighlight>


===Java 8===
===Java 8===


<lang java>
<syntaxhighlight lang="java">
import java.util.function.BiFunction;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Function;
Line 947: Line 947:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 954: Line 954:


====Partial application====
====Partial application====
<lang javascript> function addN(n) {
<syntaxhighlight lang="javascript"> function addN(n) {
var curry = function(x) {
var curry = function(x) {
return x + n;
return x + n;
Line 963: Line 963:
add2 = addN(2);
add2 = addN(2);
alert(add2);
alert(add2);
alert(add2(7));</lang>
alert(add2(7));</syntaxhighlight>


====Generic currying====
====Generic currying====
Line 969: Line 969:
Basic case - returning a curried version of a function of two arguments
Basic case - returning a curried version of a function of two arguments


<lang JavaScript>(function () {
<syntaxhighlight lang="javascript">(function () {


// curry :: ((a, b) -> c) -> a -> b -> c
// curry :: ((a, b) -> c) -> a -> b -> c
Line 1,003: Line 1,003:


})();
})();
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
<lang JavaScript>[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]</lang>
<syntaxhighlight lang="javascript">[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]</syntaxhighlight>




Functions of arbitrary arity can also be curried:
Functions of arbitrary arity can also be curried:


<lang JavaScript>(function () {
<syntaxhighlight lang="javascript">(function () {


// (arbitrary arity to fully curried)
// (arbitrary arity to fully curried)
Line 1,044: Line 1,044:
// [14, 28, 42, 56, 70, 84, 98, 112, 126, 140]
// [14, 28, 42, 56, 70, 84, 98, 112, 126, 140]


})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
<lang JavaScript>[14, 28, 42, 56, 70, 84, 98, 112, 126, 140]</lang>
<syntaxhighlight lang="javascript">[14, 28, 42, 56, 70, 84, 98, 112, 126, 140]</syntaxhighlight>


===ES6===
===ES6===


====Y combinator====
====Y combinator====
Using a definition of currying that does not imply partial application, only conversion of a function of multiple arguments, e.g.: <lang javascript>(a,b) => expr_using_a_and_b</lang>into a function that takes a series of as many function applications as that function took arguments, e.g.:<lang javascript>a => b => expr_using_a_and_b</lang>
Using a definition of currying that does not imply partial application, only conversion of a function of multiple arguments, e.g.: <syntaxhighlight lang="javascript">(a,b) => expr_using_a_and_b</syntaxhighlight>into a function that takes a series of as many function applications as that function took arguments, e.g.:<syntaxhighlight lang="javascript">a => b => expr_using_a_and_b</syntaxhighlight>


One version for functions of a set amount of arguments that takes no rest arguments, and one version for functions with rest argument. The caveat being that if the rest argument would be empty, it still requires a separate application, and multiple rest arguments cannot be curried into multiple applications, since we have to figure out the number of applications from the function signature, not the amount of arguments the user might want to send it.
One version for functions of a set amount of arguments that takes no rest arguments, and one version for functions with rest argument. The caveat being that if the rest argument would be empty, it still requires a separate application, and multiple rest arguments cannot be curried into multiple applications, since we have to figure out the number of applications from the function signature, not the amount of arguments the user might want to send it.
<lang javascript>let
<syntaxhighlight lang="javascript">let
fix = // This is a variant of the Applicative order Y combinator
fix = // This is a variant of the Applicative order Y combinator
f => (f => f(f))(g => f((...a) => g(g)(...a))),
f => (f => f(f))(g => f((...a) => g(g)(...a))),
Line 1,078: Line 1,078:
print(curriedmax(8)(4),curryrestedmax(8)(4)(),curryrestedmax(8)(4)(9,7,2));
print(curriedmax(8)(4),curryrestedmax(8)(4)(),curryrestedmax(8)(4)(9,7,2));
// 8,8,9
// 8,8,9
</syntaxhighlight>
</lang>
Neither of these handle propagation of the this value for methods, as ECMAScript 2015 (ES6) fat arrow syntax doesn't allow for this value propagation. Versions could easily be written for those cases using an outer regular function expression and use of Function.prototype.call or Function.prototype.apply. Use of Y combinator could also be removed through use of an inner named function expression instead of the anonymous fat arrow function syntax.
Neither of these handle propagation of the this value for methods, as ECMAScript 2015 (ES6) fat arrow syntax doesn't allow for this value propagation. Versions could easily be written for those cases using an outer regular function expression and use of Function.prototype.call or Function.prototype.apply. Use of Y combinator could also be removed through use of an inner named function expression instead of the anonymous fat arrow function syntax.


Line 1,085: Line 1,085:
In the most rudimentary form, for example for mapping a two-argument function over an array:
In the most rudimentary form, for example for mapping a two-argument function over an array:


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {


// curry :: ((a, b) -> c) -> a -> b -> c
// curry :: ((a, b) -> c) -> a -> b -> c
Line 1,111: Line 1,111:
// [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
// [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]


})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
<lang JavaScript>[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]</lang>
<syntaxhighlight lang="javascript">[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]</syntaxhighlight>




Or, recursively currying functions of arbitrary arity:
Or, recursively currying functions of arbitrary arity:


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {


// (arbitrary arity to fully curried)
// (arbitrary arity to fully curried)
Line 1,147: Line 1,147:
// [14, 28, 42, 56, 70, 84, 98, 112, 126, 140]
// [14, 28, 42, 56, 70, 84, 98, 112, 126, 140]


})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
<lang JavaScript>[14, 28, 42, 56, 70, 84, 98, 112, 126, 140]</lang>
<syntaxhighlight lang="javascript">[14, 28, 42, 56, 70, 84, 98, 112, 126, 140]</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==


In jq, functions are filters. Accordingly, we illustrate currying by defining plus(x) to be a filter that adds x to its input, and then define plus5 as plus(5):
In jq, functions are filters. Accordingly, we illustrate currying by defining plus(x) to be a filter that adds x to its input, and then define plus5 as plus(5):
<lang jq>
<syntaxhighlight lang="jq">
def plus(x): . + x;
def plus(x): . + x;


def plus5: plus(5);
def plus5: plus(5);
</syntaxhighlight>
</lang>


We can now use plus5 as a filter, e.g.<lang jq>3 | plus5</lang> produces 8.
We can now use plus5 as a filter, e.g.<syntaxhighlight lang="jq">3 | plus5</syntaxhighlight> produces 8.


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>
<syntaxhighlight lang="julia">
function addN(n::Number)::Function
function addN(n::Number)::Function
adder(x::Number) = n + x
adder(x::Number) = n + x
return adder
return adder
end
end
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,182: Line 1,182:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


fun curriedAdd(x: Int) = { y: Int -> x + y }
fun curriedAdd(x: Int) = { y: Int -> x + y }
Line 1,191: Line 1,191:
val sum = curriedAdd(a)(b)
val sum = curriedAdd(a)(b)
println("$a + $b = $sum")
println("$a + $b = $sum")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,200: Line 1,200:
=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
Called with a number of values lesser than the number of arguments a function memorizes the given values and returns a function waiting for the missing ones.
Called with a number of values lesser than the number of arguments a function memorizes the given values and returns a function waiting for the missing ones.
<lang scheme>
<syntaxhighlight lang="scheme">
1) just define function a binary function:
1) just define function a binary function:
{def power {lambda {:a :b} {pow :a :b}}}
{def power {lambda {:a :b} {pow :a :b}}}
Line 1,214: Line 1,214:
{S.map {power 2} {S.serie 1 10}} // S.map applies the {power 2} unary function
{S.map {power 2} {S.serie 1 10}} // S.map applies the {power 2} unary function
-> 2 4 8 16 32 64 128 256 512 1024 // to a sequence of numbers from 1 to 10
-> 2 4 8 16 32 64 128 256 512 1024 // to a sequence of numbers from 1 to 10
</syntaxhighlight>
</lang>


=={{header|Latitude}}==
=={{header|Latitude}}==


<lang>addN := {
<syntaxhighlight lang="text">addN := {
takes '[n].
takes '[n].
{
{
Line 1,226: Line 1,226:


add3 := addN 3.
add3 := addN 3.
add3 (4). ;; 7</lang>
add3 (4). ;; 7</syntaxhighlight>


Note that, because of the syntax of the language, it is not possible to call <code>addN</code> in one line the naive way.
Note that, because of the syntax of the language, it is not possible to call <code>addN</code> in one line the naive way.
<lang latitude>;; addN (3) (4). ;; Syntax error!
<syntaxhighlight lang="latitude">;; addN (3) (4). ;; Syntax error!
;; (addN (3)) (4). ;; Syntax error!
;; (addN (3)) (4). ;; Syntax error!
addN (3) call (4). ;; Works as expected.</lang>
addN (3) call (4). ;; Works as expected.</syntaxhighlight>


As a consequence, it is more common in Latitude to return new objects whose methods have meaningful names, rather than returning a curried function.
As a consequence, it is more common in Latitude to return new objects whose methods have meaningful names, rather than returning a curried function.
<lang latitude>addN := {
<syntaxhighlight lang="latitude">addN := {
takes '[n].
takes '[n].
Object clone tap {
Object clone tap {
Line 1,243: Line 1,243:
}.
}.


addN 3 do 4. ;; 7</lang>
addN 3 do 4. ;; 7</syntaxhighlight>


=={{header|LFE}}==
=={{header|LFE}}==
<lang lisp>(defun curry (f arg)
<syntaxhighlight lang="lisp">(defun curry (f arg)
(lambda (x)
(lambda (x)
(apply f
(apply f
(list arg x))))
(list arg x))))
</syntaxhighlight>
</lang>
Usage:
Usage:
<lang lisp>
<syntaxhighlight lang="lisp">
(funcall (curry #'+/2 10) 10)
(funcall (curry #'+/2 10) 10)
</syntaxhighlight>
</lang>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
<lang logtalk>
<syntaxhighlight lang="logtalk">
| ?- logtalk << call([Z]>>(call([X,Y]>>(Y is X*X), 5, R), Z is R*R), T).
| ?- logtalk << call([Z]>>(call([X,Y]>>(Y is X*X), 5, R), Z is R*R), T).
T = 625
T = 625
yes
yes
</syntaxhighlight>
</lang>


Logtalk support for lambda expressions and currying was introduced in version 2.38.0, released in December 2009.
Logtalk support for lambda expressions and currying was introduced in version 2.38.0, released in December 2009.


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>
<syntaxhighlight lang="lua">
function curry2(f)
function curry2(f)
return function(x)
return function(x)
Line 1,284: Line 1,284:
assert(add2(3) == 2+3)
assert(add2(3) == 2+3)
assert(add2(5) == 2+5)
assert(add2(5) == 2+5)
</syntaxhighlight>
</lang>
=== another implementation ===
=== another implementation ===
Proper currying, tail call without array packing/unpack.
Proper currying, tail call without array packing/unpack.
<lang lua>
<syntaxhighlight lang="lua">
local curry do
local curry do
local call,env = function(fn,...)return fn(...)end
local call,env = function(fn,...)return fn(...)end
Line 1,323: Line 1,323:
assert(add2(3) == 2+3)
assert(add2(3) == 2+3)
assert(add2(5) == 2+5)
assert(add2(5) == 2+5)
</syntaxhighlight>
</lang>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module LikeCpp {
Module LikeCpp {
divide=lambda (x, y)->x/y
divide=lambda (x, y)->x/y
Line 1,369: Line 1,369:
}
}
Joke
Joke
</syntaxhighlight>
</lang>
Without joke, can anyone answer this puzzle?
Without joke, can anyone answer this puzzle?
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Puzzle {
Module Puzzle {
Global Group F2 {
Global Group F2 {
Line 1,398: Line 1,398:
}
}
Puzzle
Puzzle
</syntaxhighlight>
</lang>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Line 1,424: Line 1,424:
=={{header|Nemerle}}==
=={{header|Nemerle}}==
Currying isn't built in to Nemerle, but is relatively straightforward to define.
Currying isn't built in to Nemerle, but is relatively straightforward to define.
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;
Line 1,443: Line 1,443:
WriteLine($"$(h(30))")
WriteLine($"$(h(30))")
}
}
}</lang>
}</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>proc addN[T](n: T): auto = (proc(x: T): T = x + n)
<syntaxhighlight lang="nim">proc addN[T](n: T): auto = (proc(x: T): T = x + n)


let add2 = addN(2)
let add2 = addN(2)
echo add2(7)</lang>
echo add2(7)</syntaxhighlight>
Alternative syntax:
Alternative syntax:
<lang nim>import sugar
<syntaxhighlight lang="nim">import sugar


proc addM[T](n: T): auto = (x: T) => x + n
proc addM[T](n: T): auto = (x: T) => x + n


let add3 = addM(3)
let add3 = addM(3)
echo add3(7)</lang>
echo add3(7)</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
OCaml has a built-in natural method of defining functions that are curried:
OCaml has a built-in natural method of defining functions that are curried:
<lang ocaml>let addnums x y = x+y (* declare a curried function *)
<syntaxhighlight lang="ocaml">let addnums x y = x+y (* declare a curried function *)


let add1 = addnums 1 (* bind the first argument to get another function *)
let add1 = addnums 1 (* bind the first argument to get another function *)
add1 42 (* apply to actually compute a result, 43 *)</lang>
add1 42 (* apply to actually compute a result, 43 *)</syntaxhighlight>
The type of <code>addnums</code> above will be <tt>int -> int -> int</tt>.
The type of <code>addnums</code> above will be <tt>int -> int -> int</tt>.


Line 1,469: Line 1,469:


You can also define a general currying higher-ordered function:
You can also define a general currying higher-ordered function:
<lang ocaml>let curry f x y = f (x,y)
<syntaxhighlight lang="ocaml">let curry f x y = f (x,y)
(* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *)</lang>
(* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *)</syntaxhighlight>
This is a function that takes a function as a parameter and returns a function that takes one of the parameters and returns ''another'' function that takes the other parameter and returns the result of applying the parameter function to the pair of arguments.
This is a function that takes a function as a parameter and returns a function that takes one of the parameters and returns ''another'' function that takes the other parameter and returns the result of applying the parameter function to the pair of arguments.


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>2 #+ curry => 2+
<syntaxhighlight lang="oforth">2 #+ curry => 2+
5 2+ .
5 2+ .
7 ok</lang>
7 ok</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(define (addN n)
(define (addN n)
(lambda (x) (+ x n)))
(lambda (x) (+ x n)))
Line 1,488: Line 1,488:
(print "(add10 4) ==> " (add10 4))
(print "(add10 4) ==> " (add10 4))
(print "(add20 4) ==> " (add20 4)))
(print "(add20 4) ==> " (add20 4)))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,497: Line 1,497:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Simple currying example with closures.
Simple currying example with closures.
<lang parigp>curriedPlus(x)=y->x+y;
<syntaxhighlight lang="parigp">curriedPlus(x)=y->x+y;
curriedPlus(1)(2)</lang>
curriedPlus(1)(2)</syntaxhighlight>
{{out}}
{{out}}
<pre>3</pre>
<pre>3</pre>
Line 1,504: Line 1,504:
=={{header|Perl}}==
=={{header|Perl}}==
This is a [[Perl|Perl 5]] example of a general curry function and curried plus using [[wp:closure (computer science)|closures]]:
This is a [[Perl|Perl 5]] example of a general curry function and curried plus using [[wp:closure (computer science)|closures]]:
<lang perl>sub curry{
<syntaxhighlight lang="perl">sub curry{
my ($func, @args) = @_;
my ($func, @args) = @_;


Line 1,518: Line 1,518:


my $plusXOne = curry(\&plusXY, 1);
my $plusXOne = curry(\&plusXY, 1);
print &$plusXOne(3), "\n";</lang>
print &$plusXOne(3), "\n";</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Phix does not support currying. The closest I can manage is very similar to my solution for closures
Phix does not support currying. The closest I can manage is very similar to my solution for closures
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">curries</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">curries</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
Line 1,541: Line 1,541:
<span style="color: #004080;">integer</span> <span style="color: #000000;">curried</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">create_curried</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"add"</span><span style="color: #0000FF;">),{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">curried</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">create_curried</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"add"</span><span style="color: #0000FF;">),{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"2+5=%d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">call_curried</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curried</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">}))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"2+5=%d\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">call_curried</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curried</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">}))</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,549: Line 1,549:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php


function curry($callable)
function curry($callable)
Line 1,643: Line 1,643:
}
}


echo json_encode(array_map(curry('product', 7), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));</lang>
echo json_encode(array_map(curry('product', 7), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));</syntaxhighlight>
{{out}}<pre>[7,14,21,28,35,42,49,56,63,70]</pre>
{{out}}<pre>[7,14,21,28,35,42,49,56,63,70]</pre>


Line 1,656: Line 1,656:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Add($x) { return { param($y) return $y + $x }.GetNewClosure() }
function Add($x) { return { param($y) return $y + $x }.GetNewClosure() }
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
& (Add 1) 2
& (Add 1) 2
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,667: Line 1,667:
</pre>
</pre>
Add each number in list to its square root:
Add each number in list to its square root:
<syntaxhighlight lang="powershell">
<lang PowerShell>
(4,9,16,25 | ForEach-Object { & (add $_) ([Math]::Sqrt($_)) }) -join ", "
(4,9,16,25 | ForEach-Object { & (add $_) ([Math]::Sqrt($_)) }) -join ", "
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,692: Line 1,692:
===Nested defs and functools.partial===
===Nested defs and functools.partial===
Since Python has had local functions with closures since around 1.0, it's always been possible to create curried functions manually:
Since Python has had local functions with closures since around 1.0, it's always been possible to create curried functions manually:
<lang python> def addN(n):
<syntaxhighlight lang="python"> def addN(n):
def adder(x):
def adder(x):
return x + n
return x + n
return adder</lang>
return adder</syntaxhighlight>


<lang python> >>> add2 = addN(2)
<syntaxhighlight lang="python"> >>> add2 = addN(2)
>>> add2
>>> add2
<function adder at 0x009F1E30>
<function adder at 0x009F1E30>
>>> add2(7)
>>> add2(7)
9</lang>
9</syntaxhighlight>


But Python also comes with a function to build partial functions (with any number of positional or keyword arguments bound in) for you. This was originally in a third-party model called functional, but was added to the stdlib functools module in 2.5. Every year or so, someone suggests either moving it into builtins because it's so useful or removing it from the stdlib entirely because it's so easy to write yourself, but it's been in the functools module since 2.5 and will probably always be there.
But Python also comes with a function to build partial functions (with any number of positional or keyword arguments bound in) for you. This was originally in a third-party model called functional, but was added to the stdlib functools module in 2.5. Every year or so, someone suggests either moving it into builtins because it's so useful or removing it from the stdlib entirely because it's so easy to write yourself, but it's been in the functools module since 2.5 and will probably always be there.
<lang python>>>> from functools import partial
<syntaxhighlight lang="python">>>> from functools import partial
>>> from operator import add
>>> from operator import add
>>> add2 = partial(add, 2)
>>> add2 = partial(add, 2)
Line 1,713: Line 1,713:
>>> double = partial(map, lambda x: x*2)
>>> double = partial(map, lambda x: x*2)
>>> print(*double(range(5)))
>>> print(*double(range(5)))
0 2 4 6 8</lang>
0 2 4 6 8</syntaxhighlight>


But for a true curried function that can take arguments one at a time via normal function calls, you have to do a bit of wrapper work to build a callable object that defers to partial until all of the arguments are available. Because of the Python's dynamic nature and flexible calling syntax, there's no way to do this in a way that works for every conceivable valid function, but there are a variety of ways that work for different large subsets. Or just use a third-party library like [https://toolz.readthedocs.io toolz] that's already done it for you:
But for a true curried function that can take arguments one at a time via normal function calls, you have to do a bit of wrapper work to build a callable object that defers to partial until all of the arguments are available. Because of the Python's dynamic nature and flexible calling syntax, there's no way to do this in a way that works for every conceivable valid function, but there are a variety of ways that work for different large subsets. Or just use a third-party library like [https://toolz.readthedocs.io toolz] that's already done it for you:
<lang python>>>> from toolz import curry
<syntaxhighlight lang="python">>>> from toolz import curry
>>> import operator
>>> import operator
>>> add = curry(operator.add)
>>> add = curry(operator.add)
Line 1,728: Line 1,728:
>>> double = map(lambda x: x*2)
>>> double = map(lambda x: x*2)
>>> print(*double(range(5)))
>>> print(*double(range(5)))
0 2 4 6 8</lang>
0 2 4 6 8</syntaxhighlight>


===Automatic curry and uncurry functions using lambdas===
===Automatic curry and uncurry functions using lambdas===
Line 1,735: Line 1,735:
We can also write a general '''curry''' function, and a corresponding '''uncurry''' function, for automatic derivation of curried and uncurried functions at run-time, without needing to import ''functools.partial'':
We can also write a general '''curry''' function, and a corresponding '''uncurry''' function, for automatic derivation of curried and uncurried functions at run-time, without needing to import ''functools.partial'':


<lang python># AUTOMATIC CURRYING AND UNCURRYING OF EXISTING FUNCTIONS
<syntaxhighlight lang="python"># AUTOMATIC CURRYING AND UNCURRYING OF EXISTING FUNCTIONS




Line 1,788: Line 1,788:




main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Manually curried using a lambda:
<pre>Manually curried using a lambda:
Line 1,817: Line 1,817:
In the second example we drop the 8 from the previous example from the stack and then use currying to join "lamb" to "balti".
In the second example we drop the 8 from the previous example from the stack and then use currying to join "lamb" to "balti".


<lang Quackery> [ ' [ ' ] swap nested join
<syntaxhighlight lang="quackery"> [ ' [ ' ] swap nested join
]'[ nested join ] is curried ( x --> [ )</lang>
]'[ nested join ] is curried ( x --> [ )</syntaxhighlight>


{{out}}
{{out}}
Line 1,846: Line 1,846:
We can easily define ''currying'' and ''uncurrying'' for two-argument functions as follows:
We can easily define ''currying'' and ''uncurrying'' for two-argument functions as follows:


<lang rsplus>
<syntaxhighlight lang="rsplus">
curry <- \(f) \(x) \(y) f(x, y)
curry <- \(f) \(x) \(y) f(x, y)
uncurry <- \(f) \(x, y) f(x)(y)
uncurry <- \(f) \(x, y) f(x)(y)
</syntaxhighlight>
</lang>


Here are some examples
Here are some examples


<lang rsplus>
<syntaxhighlight lang="rsplus">
add_curry <- curry(`+`)
add_curry <- curry(`+`)
add2 <- add_curry(2)
add2 <- add_curry(2)
add2(40)
add2(40)
uncurry(add_curry)(40, 2)
uncurry(add_curry)(40, 2)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,876: Line 1,876:
The simplest way to make a curried functions is to use curry:
The simplest way to make a curried functions is to use curry:


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(((curry +) 3) 2) ; =>5
(((curry +) 3) 2) ; =>5
</syntaxhighlight>
</lang>


As an alternative, one can use the following syntax:
As an alternative, one can use the following syntax:
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 1,889: Line 1,889:


((curried+ 3) 2) ; => 5
((curried+ 3) 2) ; => 5
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
All callable objects have an "assuming" method that can do partial application of either positional or named arguments. Here we curry the built-in subtraction operator.
All callable objects have an "assuming" method that can do partial application of either positional or named arguments. Here we curry the built-in subtraction operator.
<lang perl6>my &negative = &infix:<->.assuming(0);
<syntaxhighlight lang="raku" line>my &negative = &infix:<->.assuming(0);
say negative 1;</lang>
say negative 1;</syntaxhighlight>
{{out}}
{{out}}
<pre>-1</pre>
<pre>-1</pre>
Line 1,902: Line 1,902:
This example is modeled after the &nbsp; '''D''' &nbsp; example.
This example is modeled after the &nbsp; '''D''' &nbsp; example.
===specific version===
===specific version===
<lang rexx>/*REXX program demonstrates a REXX currying method to perform addition. */
<syntaxhighlight lang="rexx">/*REXX program demonstrates a REXX currying method to perform addition. */
say 'add 2 to 3: ' add(2, 3)
say 'add 2 to 3: ' add(2, 3)
say 'add 2 to 3 (curried):' add2(3)
say 'add 2 to 3 (curried):' add2(3)
Line 1,908: Line 1,908:
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
add: procedure; $= arg(1); do j=2 to arg(); $= $ + arg(j); end; return $
add: procedure; $= arg(1); do j=2 to arg(); $= $ + arg(j); end; return $
add2: procedure; return add( arg(1), 2)</lang>
add2: procedure; return add( arg(1), 2)</syntaxhighlight>
{{out|output|text=&nbsp; when using the defaults:}}
{{out|output|text=&nbsp; when using the defaults:}}
<pre>
<pre>
Line 1,916: Line 1,916:


===generic version===
===generic version===
<lang rexx>/*REXX program demonstrates a REXX currying method to perform addition. */
<syntaxhighlight lang="rexx">/*REXX program demonstrates a REXX currying method to perform addition. */
say 'add 2 to 3: ' add(2, 3)
say 'add 2 to 3: ' add(2, 3)
say 'add 2 to 3 (curried):' add2(3)
say 'add 2 to 3 (curried):' add2(3)
Line 1,927: Line 1,927:
return $
return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
add2: procedure; return add( arg(1), 2)</lang>
add2: procedure; return add( arg(1), 2)</syntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>


Line 1,933: Line 1,933:
The curry method was added in Ruby 1.9.1. It takes an optional arity argument, which determines the number of arguments to be passed to the proc.
The curry method was added in Ruby 1.9.1. It takes an optional arity argument, which determines the number of arguments to be passed to the proc.
If that number is not reached, the curry method returns a new curried method for the rest of the arguments. (Examples taken from the documentation).
If that number is not reached, the curry method returns a new curried method for the rest of the arguments. (Examples taken from the documentation).
<lang ruby>
<syntaxhighlight lang="ruby">
b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
p b.curry[1][2][3] #=> 6
p b.curry[1][2][3] #=> 6
Line 1,947: Line 1,947:
p b.curry(5)[1, 2][3, 4][5] #=> 15
p b.curry(5)[1, 2][3, 4][5] #=> 15
p b.curry(1)[1] #=> 1
p b.curry(1)[1] #=> 1
</syntaxhighlight>
</lang>


=={{header|Rust}}==
=={{header|Rust}}==


This is a simple currying function written in [[Rust]]:
This is a simple currying function written in [[Rust]]:
<lang rust>fn add_n(n : i32) -> impl Fn(i32) -> i32 {
<syntaxhighlight lang="rust">fn add_n(n : i32) -> impl Fn(i32) -> i32 {
move |x| n + x
move |x| n + x
}
}
Line 1,959: Line 1,959:
let adder = add_n(40);
let adder = add_n(40);
println!("The answer to life is {}.", adder(2));
println!("The answer to life is {}.", adder(2));
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<syntaxhighlight lang="scala">
<lang Scala>
def add(a: Int)(b: Int) = a + b
def add(a: Int)(b: Int) = a + b
val add5 = add(5) _
val add5 = add(5) _
add5(2)
add5(2)
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
This can be done by using lazy methods:
This can be done by using lazy methods:
<lang ruby>var adder = 1.method(:add);
<syntaxhighlight lang="ruby">var adder = 1.method(:add);
say adder(3); #=> 4</lang>
say adder(3); #=> 4</syntaxhighlight>


Or by using a generic curry function:
Or by using a generic curry function:
<lang ruby>func curry(f, *args1) {
<syntaxhighlight lang="ruby">func curry(f, *args1) {
func (*args2) {
func (*args2) {
f(args1..., args2...);
f(args1..., args2...);
Line 1,985: Line 1,985:


var adder = curry(add, 1);
var adder = curry(add, 1);
say adder(3); #=>4</lang>
say adder(3); #=>4</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
Standard ML has a built-in natural method of defining functions that are curried:
Standard ML has a built-in natural method of defining functions that are curried:
<lang sml>fun addnums (x:int) y = x+y (* declare a curried function *)
<syntaxhighlight lang="sml">fun addnums (x:int) y = x+y (* declare a curried function *)


val add1 = addnums 1 (* bind the first argument to get another function *)
val add1 = addnums 1 (* bind the first argument to get another function *)
add1 42 (* apply to actually compute a result, 43 *)</lang>
add1 42 (* apply to actually compute a result, 43 *)</syntaxhighlight>
The type of <code>addnums</code> above will be <tt>int -> int -> int</tt> (the type constraint in the declaration only being necessary because of the polymorphic nature of the <code>+</code> operator).
The type of <code>addnums</code> above will be <tt>int -> int -> int</tt> (the type constraint in the declaration only being necessary because of the polymorphic nature of the <code>+</code> operator).


Line 1,998: Line 1,998:


You can also define a general currying higher-ordered function:
You can also define a general currying higher-ordered function:
<lang sml>fun curry f x y = f(x,y)
<syntaxhighlight lang="sml">fun curry f x y = f(x,y)
(* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *)</lang>
(* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *)</syntaxhighlight>
This is a function that takes a function as a parameter and returns a function that takes one of the parameters and returns ''another'' function that takes the other parameter and returns the result of applying the parameter function to the pair of arguments.
This is a function that takes a function as a parameter and returns a function that takes one of the parameters and returns ''another'' function that takes the other parameter and returns the result of applying the parameter function to the pair of arguments.


=={{header|Swift}}==
=={{header|Swift}}==
You can return a closure (or nested function):
You can return a closure (or nested function):
<lang Swift>func addN(n:Int)->Int->Int { return {$0 + n} }
<syntaxhighlight lang="swift">func addN(n:Int)->Int->Int { return {$0 + n} }


var add2 = addN(2)
var add2 = addN(2)
println(add2) // (Function)
println(add2) // (Function)
println(add2(7)) // 9</lang>
println(add2(7)) // 9</syntaxhighlight>


Prior to Swift 3, there was a curried function definition syntax:
Prior to Swift 3, there was a curried function definition syntax:
<lang Swift>func addN(n:Int)(x:Int) -> Int { return x + n }
<syntaxhighlight lang="swift">func addN(n:Int)(x:Int) -> Int { return x + n }


var add2 = addN(2)
var add2 = addN(2)
println(add2) // (Function)
println(add2) // (Function)
println(add2(x:7)) // 9</lang>
println(add2(x:7)) // 9</syntaxhighlight>
However, there was a bug in the above syntax which forces the second parameter to always be labeled. As of Swift 1.2, you could explicitly make the second parameter not labeled:
However, there was a bug in the above syntax which forces the second parameter to always be labeled. As of Swift 1.2, you could explicitly make the second parameter not labeled:
<lang Swift>func addN(n:Int)(_ x:Int) -> Int { return x + n }
<syntaxhighlight lang="swift">func addN(n:Int)(_ x:Int) -> Int { return x + n }


var add2 = addN(2)
var add2 = addN(2)
println(add2) // (Function)
println(add2) // (Function)
println(add2(7)) // 9</lang>
println(add2(7)) // 9</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
The simplest way to do currying in Tcl is via an interpreter alias:
The simplest way to do currying in Tcl is via an interpreter alias:
<lang tcl>interp alias {} addone {} ::tcl::mathop::+ 1
<syntaxhighlight lang="tcl">interp alias {} addone {} ::tcl::mathop::+ 1
puts [addone 6]; # => 7</lang>
puts [addone 6]; # => 7</syntaxhighlight>
Tcl doesn't support automatic creation of curried functions though; the general variadic nature of a large proportion of Tcl commands makes that impractical.
Tcl doesn't support automatic creation of curried functions though; the general variadic nature of a large proportion of Tcl commands makes that impractical.
===History===
===History===
Line 2,045: Line 2,045:
A two-argument function which subtracts is arguments from 10, and then subtracts five:
A two-argument function which subtracts is arguments from 10, and then subtracts five:


<lang txrlisp>(op - 10 @1 @2 5)</lang>
<syntaxhighlight lang="txrlisp">(op - 10 @1 @2 5)</syntaxhighlight>


TXR Lisp doesn't have a predefined function or operator for currying. A function can be manually curried. For instance, the three-argument named function: <code>(defun f (x y z) (* (+ x y) z))</code> can be curried by hand to produce a function <code>g</code> like this:
TXR Lisp doesn't have a predefined function or operator for currying. A function can be manually curried. For instance, the three-argument named function: <code>(defun f (x y z) (* (+ x y) z))</code> can be curried by hand to produce a function <code>g</code> like this:


<lang txrlisp>(defun g (x)
<syntaxhighlight lang="txrlisp">(defun g (x)
(lambda (y)
(lambda (y)
(lambda (z)
(lambda (z)
(* (+ x y) z))))</lang>
(* (+ x y) z))))</syntaxhighlight>


Or, by referring to the definition of <code>f</code>:
Or, by referring to the definition of <code>f</code>:


<lang txrlisp>(defun g (x)
<syntaxhighlight lang="txrlisp">(defun g (x)
(lambda (y)
(lambda (y)
(lambda (z)
(lambda (z)
(f x y z))))</lang>
(f x y z))))</syntaxhighlight>


Since a three-argument function can be defined directly, and has advantages like diagnosing incorrect calls which pass fewer than three or more than three arguments, currying is not useful in this language. Similar reasoning applies as given in the "Why not real currying/uncurrying?" paragraph under the Design Rationale of Scheme's SRFI 26.
Since a three-argument function can be defined directly, and has advantages like diagnosing incorrect calls which pass fewer than three or more than three arguments, currying is not useful in this language. Similar reasoning applies as given in the "Why not real currying/uncurrying?" paragraph under the Design Rationale of Scheme's SRFI 26.


=={{header|Vala}}==
=={{header|Vala}}==
<lang Vala>delegate double Dbl_Op(double d);
<syntaxhighlight lang="vala">delegate double Dbl_Op(double d);


Dbl_Op curried_add(double a) {
Dbl_Op curried_add(double a) {
Line 2,074: Line 2,074:
double sum2 = curried_add(2.0) (curried_add(3.0)(4.0)); //sum2 = 9
double sum2 = curried_add(2.0) (curried_add(3.0)(4.0)); //sum2 = 9
print(@"$sum2\n");
print(@"$sum2\n");
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,090: Line 2,090:
Uses generics and lambdas returning lambdas.
Uses generics and lambdas returning lambdas.


<lang vbnet>Option Explicit On
<syntaxhighlight lang="vbnet">Option Explicit On
Option Infer On
Option Infer On
Option Strict On
Option Strict On
Line 2,110: Line 2,110:


' And so on.
' And so on.
End Module</lang>
End Module</syntaxhighlight>


Test code:
Test code:
<lang vbnet>Module Main
<syntaxhighlight lang="vbnet">Module Main
' An example binary function.
' An example binary function.
Function Add(a As Integer, b As Integer) As Integer
Function Add(a As Integer, b As Integer) As Integer
Line 2,141: Line 2,141:
Console.WriteLine(substringStartingAt1(4))
Console.WriteLine(substringStartingAt1(4))
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>


===Late-binding approach===
===Late-binding approach===
Line 2,153: Line 2,153:
Due to VB's syntax, with indexers using parentheses, late-bound invocation expressions are compiled as invocations of the default property of the receiver. Thus, it is not possible to perform a late-bound delegate invocation. This limitation can, however, be circumvented, by declaring a type that wraps a delegate and defines a default property that invokes the delegate. Furthermore, by making this type what is essentially a discriminated union of a delegate and a result and guaranteeing that all invocations return another instance of this type, it is possible for the entire system to work with Option Strict on.
Due to VB's syntax, with indexers using parentheses, late-bound invocation expressions are compiled as invocations of the default property of the receiver. Thus, it is not possible to perform a late-bound delegate invocation. This limitation can, however, be circumvented, by declaring a type that wraps a delegate and defines a default property that invokes the delegate. Furthermore, by making this type what is essentially a discriminated union of a delegate and a result and guaranteeing that all invocations return another instance of this type, it is possible for the entire system to work with Option Strict on.


<lang vbnet>Option Explicit On
<syntaxhighlight lang="vbnet">Option Explicit On
Option Infer On
Option Infer On
Option Strict On
Option Strict On
Line 2,203: Line 2,203:
New CurryDelegate(Function(arg As Object) DynamicCurry(func, collectedArgs.Add(arg))))
New CurryDelegate(Function(arg As Object) DynamicCurry(func, collectedArgs.Add(arg))))
End Function
End Function
End Module</lang>
End Module</syntaxhighlight>


Test code:
Test code:
<lang vbnet>Module Program
<syntaxhighlight lang="vbnet">Module Program
Function Add(a As Integer, b As Integer) As Integer
Function Add(a As Integer, b As Integer) As Integer
Return a + b
Return a + b
Line 2,233: Line 2,233:
End Sub
End Sub
End Module
End Module
</syntaxhighlight>
</lang>


{{out|note=for both versions}}
{{out|note=for both versions}}
Line 2,247: Line 2,247:
=={{header|Wortel}}==
=={{header|Wortel}}==
The <code>\</code> operator takes a function and an argument and partial applies the argument to the function. The <code>&\</code> works like the <code>\</code> operator but can also take an array literal and partial applies all the arguments in the array.
The <code>\</code> operator takes a function and an argument and partial applies the argument to the function. The <code>&\</code> works like the <code>\</code> operator but can also take an array literal and partial applies all the arguments in the array.
<lang wortel>@let {
<syntaxhighlight lang="wortel">@let {
addOne \+ 1
addOne \+ 1
subtractFrom1 \- 1
subtractFrom1 \- 1
Line 2,266: Line 2,266:
!addOne_2 5 ; returns 6
!addOne_2 5 ; returns 6
]]
]]
}</lang>
}</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Rust}}
{{trans|Rust}}
<lang ecmascript>var addN = Fn.new { |n| Fn.new { |x| n + x } }
<syntaxhighlight lang="ecmascript">var addN = Fn.new { |n| Fn.new { |x| n + x } }


var adder = addN.call(40)
var adder = addN.call(40)
System.print("The answer to life is %(adder.call(2)).")</lang>
System.print("The answer to life is %(adder.call(2)).")</syntaxhighlight>


{{out}}
{{out}}
Line 2,283: Line 2,283:
{{works with|Amstrad CPC}}
{{works with|Amstrad CPC}}
The BIOS call <code>&BB75</code> takes HL as input (as if it were an x,y coordinate pair) and outputs a video memory address into HL. Using a fixed input of HL=0x0101 we can effectively reset the drawing cursor to the top left corner of the screen.
The BIOS call <code>&BB75</code> takes HL as input (as if it were an x,y coordinate pair) and outputs a video memory address into HL. Using a fixed input of HL=0x0101 we can effectively reset the drawing cursor to the top left corner of the screen.
<lang z80>macro ResetCursors
<syntaxhighlight lang="z80">macro ResetCursors
ld hl,&0101
ld hl,&0101
call &BB75
call &BB75
endm</lang>
endm</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
zkl doesn't support currying per se (recompilation of f with fixed input to create a new function), it does support partial application, for all objects, for any [number of] positional parameters to create an object of reduced arity.
zkl doesn't support currying per se (recompilation of f with fixed input to create a new function), it does support partial application, for all objects, for any [number of] positional parameters to create an object of reduced arity.
<lang zkl>addOne:= Op("+").fp(1); addOne(5) //-->6
<syntaxhighlight lang="zkl">addOne:= Op("+").fp(1); addOne(5) //-->6
minusOne:=Op("-").fp1(1); minusOne(5) //-->4, note that this fixed 1 as the second parameter
minusOne:=Op("-").fp1(1); minusOne(5) //-->4, note that this fixed 1 as the second parameter
// fix first and third parameters:
// fix first and third parameters:
foo:=String.fpM("101","<foo>","</foo>"); foo("zkl"); //-->"<foo>zkl</foo>"
foo:=String.fpM("101","<foo>","</foo>"); foo("zkl"); //-->"<foo>zkl</foo>"
fcn g(x){x+1} f:=fcn(f,x){f(x)+x}.fp(g); f(5); //-->11
fcn g(x){x+1} f:=fcn(f,x){f(x)+x}.fp(g); f(5); //-->11
f:=fcn(f,x){f(x)+x}.fp(fcn(x){x+1}); // above with lambdas all the way down</lang>
f:=fcn(f,x){f(x)+x}.fp(fcn(x){x+1}); // above with lambdas all the way down</syntaxhighlight>