Currying: Difference between revisions

19,010 bytes added ,  2 months ago
m
m (→‎another implementation: fix header markup @ lua)
 
(42 intermediate revisions by 27 users not shown)
Line 10:
[[Category:Functions and subroutines]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F addN(n)
F adder(x)
R x + @=n
R adder
 
V add2 = addN(2)
V add3 = addN(3)
print(add2(7))
print(add3(7))</syntaxhighlight>
 
{{out}}
<pre>
9
10
</pre>
 
=={{header|Ada}}==
Ada lacks explicit support for currying, or indeed just about any form of functional programming at all. However if one views generic subprograms as approximately equivalent to higher order functions, and generic packages as approximately equivalent to closures, then the desired functionality can still be achieved. The chief limitation is that separate generic support packages must exist for each arity that is to be curried.
 
Support package spec:
<syntaxhighlight lang="ada">generic
type Argument_1 (<>) is limited private;
type Argument_2 (<>) is limited private;
type Argument_3 (<>) is limited private;
type Return_Value (<>) is limited private;
 
with function Func
(A : in Argument_1;
B : in Argument_2;
C : in Argument_3)
return Return_Value;
package Curry_3 is
 
generic
First : in Argument_1;
package Apply_1 is
 
generic
Second : in Argument_2;
package Apply_2 is
 
function Apply_3
(Third : in Argument_3)
return Return_Value;
 
end Apply_2;
 
end Apply_1;
 
end Curry_3;</syntaxhighlight>
 
Support package body:
<syntaxhighlight lang="ada">package body Curry_3 is
 
package body Apply_1 is
 
package body Apply_2 is
 
function Apply_3
(Third : in Argument_3)
return Return_Value is
begin
return Func (First, Second, Third);
end Apply_3;
 
end Apply_2;
 
end Apply_1;
 
end Curry_3;</syntaxhighlight>
 
Currying a function:
<syntaxhighlight lang="ada">with Curry_3, Ada.Text_IO;
 
procedure Curry_Test is
 
function Sum
(X, Y, Z : in Integer)
return Integer is
begin
return X + Y + Z;
end Sum;
 
package Curried is new Curry_3
(Argument_1 => Integer,
Argument_2 => Integer,
Argument_3 => Integer,
Return_Value => Integer,
Func => Sum);
 
package Sum_5 is new Curried.Apply_1 (5);
package Sum_5_7 is new Sum_5.Apply_2 (7);
Result : Integer := Sum_5_7.Apply_3 (3);
 
begin
 
Ada.Text_IO.Put_Line ("Five plus seven plus three is" & Integer'Image (Result));
 
end Curry_Test;</syntaxhighlight>
 
Output:
<pre>Five plus seven plus three is 15</pre>
 
=={{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:
<langsyntaxhighlight lang="aime">ri(list l)
{
l[0] = apply.apply(l[0]);
Line 26 ⟶ 132:
0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre> 000,040,000,000</pre>
Line 32 ⟶ 138:
=={{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]].
<langsyntaxhighlight lang="algol68"># Raising a function to a power #
 
MODE FUN = PROC (REAL) REAL;
Line 41 ⟶ 147:
 
REAL x = read real;
print ((new line, sin (3 * x), 3 * sin (x) - 4 * (sin ** 3) (x)))</langsyntaxhighlight>
 
=={{header|AppleScript}}==
Line 47 ⟶ 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.
 
<langsyntaxhighlight AppleScriptlang="applescript">-- curry :: (Script|Handler) -> Script
on curry(f)
script
Line 144 ⟶ 250:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>{«script», «script», 5, {7, 14, 21, 28, 35, 42, 49, 56, 63, 70}}</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">addN: function [n][
return function [x] with 'n [
return x + n
]
]
 
add2: addN 2
add3: addN 3
 
do [
print add2 7
print add3 7
]</syntaxhighlight>
 
{{out}}
 
<pre>9
10</pre>
 
=={{header|BASIC}}==
==={{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:
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Type CurriedAdd
As Integer i
Declare Function add(As Integer) As Integer
End Type
 
Function CurriedAdd.add(j As Integer) As Integer
Return i + j
End Function
 
Function add (i As Integer) as CurriedAdd
Return Type<CurriedAdd>(i)
End Function
 
Print "3 + 4 ="; add(3).add(4)
Print "2 + 6 ="; add(2).add(6)
Sleep</syntaxhighlight>
 
{{out}}
<pre>
3 + 4 = 7
2 + 6 = 8
</pre>
 
==={{header|Visual Basic .NET}}===
'''Compiler:''' Roslyn Visual Basic (language version >=15.3)
 
Functions are not curried in VB.NET, so this entry details functions that take a function and return functions that act as if the original function were curried (i.e. each takes one parameter and returns another function that takes one parameter, with the function for which all parameters of the original function are supplied calling the original function with those arguments.
 
====Fixed-arity approach====
Uses generics and lambdas returning lambdas.
<syntaxhighlight lang="vbnet">Option Explicit On
Option Infer On
Option Strict On
 
Module Currying
' The trivial curry.
Function Curry(Of T1, TResult)(func As Func(Of T1, TResult)) As Func(Of T1, TResult)
' At least satisfy the implicit contract that the result isn't reference-equal to the original function.
Return Function(a) func(a)
End Function
 
Function Curry(Of T1, T2, TResult)(func As Func(Of T1, T2, TResult)) As Func(Of T1, Func(Of T2, TResult))
Return Function(a) Function(b) func(a, b)
End Function
 
Function Curry(Of T1, T2, T3, TResult)(func As Func(Of T1, T2, T3, TResult)) As Func(Of T1, Func(Of T2, Func(Of T3, TResult)))
Return Function(a) Function(b) Function(c) func(a, b, c)
End Function
 
' And so on.
End Module</syntaxhighlight>
 
Test code:
<syntaxhighlight lang="vbnet">Module Main
' An example binary function.
Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
 
Sub Main()
Dim curriedAdd = Curry(Of Integer, Integer, Integer)(AddressOf Add)
Dim add2To = curriedAdd(2)
 
Console.WriteLine(Add(2, 3))
Console.WriteLine(add2To(3))
Console.WriteLine(curriedAdd(2)(3))
 
' An example ternary function.
Dim substring = Function(s As String, startIndex As Integer, length As Integer) s.Substring(startIndex, length)
Dim curriedSubstring = Curry(substring)
 
Console.WriteLine(substring("abcdefg", 2, 3))
Console.WriteLine(curriedSubstring("abcdefg")(2)(3))
 
' The above is just syntax sugar for this (a call to the Invoke() method of System.Delegate):
Console.WriteLine(curriedSubstring.Invoke("abcdefg").Invoke(2).Invoke(3))
 
Dim substringStartingAt1 = curriedSubstring("abcdefg")(1)
Console.WriteLine(substringStartingAt1(2))
Console.WriteLine(substringStartingAt1(4))
End Sub
End Module</syntaxhighlight>
 
====Late-binding approach====
 
{{libheader|.NET Core|2=>=1.0}}
or both
{{libheader|.NET Framework|2=>=4.5}}
and
{{libheader|System.Collections.Immutable|1.5.0}}
 
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.
 
<syntaxhighlight lang="vbnet">Option Explicit On
Option Infer On
Option Strict On
 
Module CurryingDynamic
' Cheat visual basic's syntax by defining a type that can be the receiver of what appears to be a method call.
' Needless to say, this is not idiomatic VB.
Class CurryDelegate
ReadOnly Property Value As Object
ReadOnly Property Target As [Delegate]
 
Sub New(value As Object)
Dim curry = TryCast(value, CurryDelegate)
If curry IsNot Nothing Then
Me.Value = curry.Value
Me.Target = curry.Target
ElseIf TypeOf value Is [Delegate] Then
Me.Target = DirectCast(value, [Delegate])
Else
Me.Value = value
End If
End Sub
 
' CurryDelegate could also work as a dynamic n-ary function delegate, if an additional ParamArray argument were to be added.
Default ReadOnly Property Invoke(arg As Object) As CurryDelegate
Get
If Me.Target Is Nothing Then Throw New InvalidOperationException("All curried parameters have already been supplied")
 
Return New CurryDelegate(Me.Target.DynamicInvoke({arg}))
End Get
End Property
 
' A syntactically natural way to assert that the currying is complete and that the result is of the specified type.
Function Unwrap(Of T)() As T
If Me.Target IsNot Nothing Then Throw New InvalidOperationException("Some curried parameters have not yet been supplied.")
Return DirectCast(Me.Value, T)
End Function
End Class
 
Function DynamicCurry(func As [Delegate]) As CurryDelegate
Return DynamicCurry(func, ImmutableList(Of Object).Empty)
End Function
 
' Use ImmutableList to create a new list every time any curried subfunction is called avoiding multiple or repeated
' calls interfering with each other.
Private Function DynamicCurry(func As [Delegate], collectedArgs As ImmutableList(Of Object)) As CurryDelegate
Return If(collectedArgs.Count = func.Method.GetParameters().Length,
New CurryDelegate(func.DynamicInvoke(collectedArgs.ToArray())),
New CurryDelegate(Function(arg As Object) DynamicCurry(func, collectedArgs.Add(arg))))
End Function
End Module</syntaxhighlight>
 
Test code:
<syntaxhighlight lang="vbnet">Module Program
Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
 
Sub Main()
' A delegate for the function must be created in order to eagerly perform overload resolution.
Dim curriedAdd = DynamicCurry(New Func(Of Integer, Integer, Integer)(AddressOf Add))
Dim add2To = curriedAdd(2)
 
Console.WriteLine(add2To(3).Unwrap(Of Integer))
Console.WriteLine(curriedAdd(2)(3).Unwrap(Of Integer))
 
Dim substring = Function(s As String, i1 As Integer, i2 As Integer) s.Substring(i1, i2)
Dim curriedSubstring = DynamicCurry(substring)
 
Console.WriteLine(substring("abcdefg", 2, 3))
Console.WriteLine(curriedSubstring("abcdefg")(2)(3).Unwrap(Of String))
 
' The trickery of using a parameterized default property also makes it appear that the "delegate" has an Invoke() method.
Console.WriteLine(curriedSubstring.Invoke("abcdefg").Invoke(2).Invoke(3).Unwrap(Of String))
 
Dim substringStartingAt1 = curriedSubstring("abcdefg")(1)
Console.WriteLine(substringStartingAt1(2).Unwrap(Of String))
Console.WriteLine(substringStartingAt1(4).Unwrap(Of String))
End Sub
End Module
</syntaxhighlight>
 
{{out|note=for both versions}}
<pre>5
5
5
cde
cde
cde
bc
bcde</pre>
 
=={{header|Binary Lambda Calculus}}==
 
In BLC, all multi argument functions are necessarily achieved by currying, since lambda calculus functions (lambdas) are single argument. A good example is the Church numeral 2, which given a function f and an argument x, applies f twice on x: C2 = \f. (\x. f (f x)). This is written in BLC as
 
<pre>00 00 01 110 01 110 01</pre>
 
where 00 denotes lambda, 01 denotes application, and 1^n0 denotes the variable bound by the n'th enclosing lambda. Which is all there is to BCL!
 
=={{header|BQN}}==
All BQN functions can only take 2 arguments, signified by <code>𝕨</code> and <code>𝕩</code> in block definitions. Hence, currying is largely done with the help of combinators like Before(<code>⊸</code>) and After(<code>⟜</code>).
 
Adapted from [[Currying#J|J]].
<syntaxhighlight lang="bqn">Plus3 ← 3⊸+
Plus3_1 ← +⟜3
 
•Show Plus3 1
•Show Plus3_1 1</syntaxhighlight>
<syntaxhighlight lang="text">4
4</syntaxhighlight>
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include<stdarg.h>
#include<stdio.h>
Line 181 ⟶ 518:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 191 ⟶ 528:
</pre>
 
=={{header|C sharp|C#}}==
This shows how to create syntactically natural currying functions in [[C sharp|C#]].
<langsyntaxhighlight lang="csharp">public delegate int Plus(int y);
public delegate Plus CurriedPlus(int x);
public static CurriedPlus plus =
Line 201 ⟶ 538:
int sum = plus(3)(4); // sum = 7
int sum2= plus(2)(plus(3)(4)) // sum2 = 9
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 208 ⟶ 545:
=={{header|Ceylon}}==
{{trans|Groovy}}
<langsyntaxhighlight lang="ceylon">shared void run() {
function divide(Integer x, Integer y) => x / y;
Line 217 ⟶ 554:
a third is ``partsOf120(3)``
and a quarter is ``partsOf120(4)``");
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(def plus-a-hundred (partial + 100))
(assert (=
(plus-a-hundred 1)
101))
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun curry (function &rest args-1)
(lambda (&rest args-2)
(apply function (append args-1 args-2))))
</syntaxhighlight>
</lang>
 
Usage:
<langsyntaxhighlight lang="lisp">
(funcall (curry #'+ 10) 10)
 
20
</syntaxhighlight>
</lang>
 
=={{header|Crystal}}==
Crystal allows currying procs with either <code>Proc#partial</code> or by manually creating closures:
 
<syntaxhighlight lang="ruby">add_things = ->(x1 : Int32, x2 : Int32, x3 : Int32) { x1 + x2 + x3 }
add_curried = add_things.partial(2, 3)
add_curried.call(4) #=> 9
 
def add_two_things(x1)
return ->(x2 : Int32) {
->(x3 : Int32) { x1 + x2 + x3 }
}
end
add13 = add_two_things(3).call(10)
add13.call(5) #=> 18</syntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.functional;
 
Line 250 ⟶ 602:
writeln("Add 2 to 3: ", add(2, 3));
writeln("Add 2 to 3 (curried): ", add2(3));
}</langsyntaxhighlight>
{{out}}
<pre>Add 2 to 3: 5
Add 2 to 3 (curried): 5</pre>
 
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Currying;
 
{$APPTYPE CONSOLE}
{$R *.res}
 
uses
System.SysUtils;
 
var
Plus: TFunc<Integer, TFunc<Integer, Integer>>;
 
begin
Plus :=
function(x: Integer): TFunc<Integer, Integer>
begin
result :=
function(y: Integer): Integer
begin
result := x + y;
end;
end;
 
Writeln(Plus(3)(4));
Writeln(Plus(2)(Plus(3)(4)));
readln;
end.
</syntaxhighlight>
{{out}}
<pre>
7
9
</pre>
 
=={{header|EchoLisp}}==
[[EchoLisp]] has native support for curry, which is implemented thru closures, as shown in [[CommonLisp#Common_Lisp|Common Lisp]] .
<syntaxhighlight lang="text">
;;
;; curry functional definition
Line 277 ⟶ 666:
(curry * 2 3 (+ 2 2))
→ (λ _#:g1004 (#apply-curry #* (2 3 4) _#:g1004))
</syntaxhighlight>
</lang>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module CurryPower {
@Inject Console console;
void run() {
function Int(Int, Int) divide = (x,y) -> x / y;
function Int(Int) half = divide(_, 2);
function Int(Int) partsOf120 = divide(120, _);
 
console.print($|half of a dozen is {half(12)}
|half of 120 is {partsOf120(2)}
|a third is {partsOf120(3)}
|and a quarter is {partsOf120(4)}
);
}
}
</syntaxhighlight>
 
{{out}}
<pre>
half of a dozen is 6
half of 120 is 60
a third is 40
and a quarter is 30
</pre>
 
=={{header|Eero}}==
<langsyntaxhighlight lang="objc">#import <stdio.h>
 
int main()
Line 294 ⟶ 709:
 
return 0
</syntaxhighlight>
</lang>
Alternative implementation (there are a few ways to express blocks/lambdas):
<langsyntaxhighlight lang="objc">#import <stdio.h>
 
int main()
Line 308 ⟶ 723:
 
return 0
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
Line 322 ⟶ 737:
 
where FUNCTION [ANY, TUPLE [Y], Z] denotes the type ''Y'' → ''Z'' (agents taking as argument a tuple with a single argument of type Y and returning a result of type Z), which is indeed the type of the agent expression used on the next-to-last line to define the "Result" of g.
 
=={{header|Elixir}}==
 
<pre>
iex(1)> plus = fn x, y -> x + y end
#Function<41.125776118/2 in :erl_eval.expr/6>
iex(2)> plus.(3, 5)
8
iex(3)> plus5 = &plus.(5, &1)
#Function<42.125776118/1 in :erl_eval.expr/6>
iex(4)> plus5.(3)
8
</pre>
 
=={{header|EMal}}==
{{trans|C#}}
<syntaxhighlight lang="emal">
fun plus = fun by int y
return int by int x do return x + y end
end
int sum0 = plus(3)(4)
int sum1 = plus(2)(plus(3)(4))
writeLine(sum0)
writeLine(sum1)
</syntaxhighlight>
{{out}}
<pre>
7
9
</pre>
 
=={{header|Erlang}}==
Line 327 ⟶ 772:
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.
 
<langsyntaxhighlight lang="erlang">
-module(currying).
 
Line 390 ⟶ 835:
erlang:error(badarg)
end.
</syntaxhighlight>
</lang>
 
 
Line 430 ⟶ 875:
F# is largely based on ML and has a built-in natural method of defining functions that are curried:
 
<langsyntaxhighlight lang="fsharp">let addN n = (+) n</langsyntaxhighlight>
 
<langsyntaxhighlight lang="fsharp">> let add2 = addN 2;;
 
val add2 : (int -> int)
Line 439 ⟶ 884:
val it : (int -> int) = <fun:addN@1>
> add2 7;;
val it : int = 9</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">IN: scratchpad 2 [ 3 + ] curry
 
--- Data stack:
Line 449 ⟶ 894:
 
--- Data stack:
5</langsyntaxhighlight>
Currying doesn't need to be an atomic operation. <tt>compose</tt> lets you combine quotations.
<langsyntaxhighlight lang="factor">IN: scratchpad [ 3 4 ] [ 5 + ] compose
 
--- Data stack:
Line 459 ⟶ 904:
--- Data stack:
3
9</langsyntaxhighlight>
 
You can even treat quotations as sequences.
<langsyntaxhighlight lang="factor">IN: scratchpad { 1 2 3 4 5 } [ 1 + ] { 2 / } append map
 
--- Data stack:
{ 1 1+1/2 2 2+1/2 3 }</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="factor">USE: fry
IN: scratchpad 2 3 '[ _ _ + ]
 
--- Data stack:
[ 2 3 + ]</langsyntaxhighlight>
 
Use <tt>@</tt> to insert the contents of a quotation into another quotation.
<langsyntaxhighlight lang="factor">IN: scratchpad { 1 2 3 4 5 } [ 1 + ] '[ 2 + @ ] map
 
--- Data stack:
{ 4 5 6 7 8 }</langsyntaxhighlight>
 
=={{header|Forth}}==
{{trans|Common Lisp}}
<langsyntaxhighlight lang="forth">: curry ( x xt1 -- xt2 )
swap 2>r :noname r> postpone literal r> compile, postpone ; ;
 
5 ' + curry constant +5
5 +5 execute .
7 +5 execute .</langsyntaxhighlight>
 
{{out}}
<pre>10 12</pre>
 
=={{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:
<lang freebasic>' FB 1.05.0 Win64
 
=={{header|Fōrmulæ}}==
Type CurriedAdd
As Integer i
Declare Function add(As Integer) As Integer
End Type
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Currying}}
Function CurriedAdd.add(j As Integer) As Integer
Return i + j
End Function
 
'''Solution'''
Function add (i As Integer) as CurriedAdd
Return Type<CurriedAdd>(i)
End Function
 
In Fōrmulæ, a function is just a named lambda expression, and a function call is just a lambda application.
Print "3 + 4 ="; add(3).add(4)
Print "2 + 6 ="; add(2).add(6)
Sleep</lang>
 
The following is a simple definition of a lambda expression:
{{out}}
<pre>
3 + 4 = 7
2 + 6 = 8
</pre>
 
=={{header|[[File:Fōrmulæ}}== - Currying 01.png]]
 
When a lambda application is called with the same number of arguments, the result is the habitual:
 
[[File:Fōrmulæ - Currying 02.png]]
 
[[File:Fōrmulæ - Currying 03.png]]
 
However, if a less number of parameters is applied, currying is performed. Notice that the result is another lambda expression.
 
[[File:Fōrmulæ - Currying 04.png]]
 
[[File:Fōrmulæ - Currying 05.png]]
 
Because the result is a lambda expression, it can be used in a lambda application, so we must get the same result:
 
[[File:Fōrmulæ - Currying 06.png]]
 
[[File:Fōrmulæ - Currying 03.png]]
 
Using functions:
 
[[File:Fōrmulæ - Currying 07.png]]
 
[[File:Fōrmulæ - Currying 08.png]]
 
=={{header|GDScript}}==
{{trans|Python}}
 
Uses Godot 4's lambdas. This runs as a script attached to a node.
<syntaxhighlight lang="gdscript">
extends Node
 
func addN(n: int) -> Callable:
In [http://wiki.formulae.org/Currying this] page you can see the solution of this task.
return func(x):
return n + x
 
func _ready():
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
# Test currying
var add2 := addN(2)
print(add2.call(7))
 
get_tree().quit() # Exit
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
</syntaxhighlight>
 
=={{header|Go}}==
Line 533 ⟶ 999:
[http://golang.org/ref/spec#Method_values Method values] were added
in [http://golang.org/doc/go1.1#method_values Go 1.1].
<langsyntaxhighlight lang="go">package main
 
import (
Line 569 ⟶ 1,035:
fmt.Println("2 + 4 =", fn2(a, 4))
fmt.Println("3 + 5 =", fn2(Foo(3), 5))
}</langsyntaxhighlight>
[http://play.golang.org/p/0YL9YTe-9V Run on the Go Playground.]
 
Line 577 ⟶ 1,043:
 
Example:
<langsyntaxhighlight lang="groovy">def divide = { Number x, Number y ->
x / y
}
Line 583 ⟶ 1,049:
def partsOf120 = divide.curry(120)
 
println "120: half: ${partsOf120(2)}, third: ${partsOf120(3)}, quarter: ${partsOf120(4)}"</langsyntaxhighlight>
 
Results:
Line 592 ⟶ 1,058:
 
Example (using the same "divide()" closure as before):
<langsyntaxhighlight lang="groovy">def half = divide.rcurry(2)
def third = divide.rcurry(3)
def quarter = divide.rcurry(4)
 
println "30: half: ${half(30)}; third: ${third(30)}, quarter: ${quarter(30)}"</langsyntaxhighlight>
 
Results:
Line 605 ⟶ 1,071:
 
=={{header|Haskell}}==
Likewise in Haskell, function type signatures show the currying-based structure of functions (note: "<langsyntaxhighlight lang="haskell">\ -></langsyntaxhighlight>" is Haskell's syntax for anonymous functions, in which the sign <langsyntaxhighlight lang="haskell">\</langsyntaxhighlight> has been chosen for its resemblance to the Greek letter λ (lambda); it is followed by a list of space-separated arguments, and the arrow <langsyntaxhighlight lang="haskell">-></langsyntaxhighlight> separates the arguments list from the function body)
Prelude> let plus = \x y -> x + y
Line 621 ⟶ 1,087:
8
 
In fact, the Haskell definition <langsyntaxhighlight lang="haskell">\x y -> x + y</langsyntaxhighlight> is merely [[wp:syntactic sugar|syntactic sugar]] for <langsyntaxhighlight lang="haskell">\x -> \y -> x + y</langsyntaxhighlight>, which has exactly the same type signature:
 
Prelude> let nested_plus = \x -> \y -> x + y
Line 628 ⟶ 1,094:
 
=={{header|Hy}}==
<langsyntaxhighlight lang="hy">(defn addN [n]
(fn [x]
(+ x n)))</langsyntaxhighlight>
<langsyntaxhighlight lang="hy">=> (setv add2 (addN 2))
=> (add2 7)
9
 
=> ((addN 3) 4)
7</langsyntaxhighlight>
 
==Icon and {{header|Unicon}}==
Line 643 ⟶ 1,109:
used.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
add2 := addN(2)
write("add2(7) = ",add2(7))
Line 655 ⟶ 1,121:
procedure makeProc(A)
return (@A[1], A[1])
end</langsyntaxhighlight>
 
{{Out}}
Line 667 ⟶ 1,133:
=={{header|Io}}==
A general currying function written in the [[Io]] programming language:
<langsyntaxhighlight lang="io">curry := method(fn,
a := call evalArgs slice(1)
block(
Line 678 ⟶ 1,144:
increment := curry( method(a,b,a+b), 1 )
increment call(5)
// result => 6</langsyntaxhighlight>
 
=={{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.
'''Example''':<langsyntaxhighlight lang="j"> threePlus=: 3&+
threePlus 7
10
Line 689 ⟶ 1,155:
halve 20
10
someParabola =: _2 3 1 &p. NB. x^2 + 3x - 2</langsyntaxhighlight>
 
'''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''': J's adverbs and conjunctions (such as <code>&</code>) will curry themselves when necessary. Thus, for example:
 
<syntaxhighlight lang="j"> with2=: &2
+with2 3
5</syntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java5"> public class Currier<ARG1, ARG2, RET> {
public interface CurriableFunctor<ARG1, ARG2, RET> {
RET evaluate(ARG1 arg1, ARG2 arg2);
Line 731 ⟶ 1,203:
System.out.println(add5.evaluate(new Integer(2)));
}
}</langsyntaxhighlight>
 
===Java 8===
 
<langsyntaxhighlight lang="java">
import java.util.function.BiFunction;
import java.util.function.Function;
Line 770 ⟶ 1,242:
}
}
</syntaxhighlight>
</lang>
 
=={{header|JavaScript}}==
Line 777 ⟶ 1,249:
 
====Partial application====
<langsyntaxhighlight lang="javascript"> function addN(n) {
var curry = function(x) {
return x + n;
Line 786 ⟶ 1,258:
add2 = addN(2);
alert(add2);
alert(add2(7));</langsyntaxhighlight>
 
====Generic currying====
Line 792 ⟶ 1,264:
Basic case - returning a curried version of a function of two arguments
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// curry :: ((a, b) -> c) -> a -> b -> c
Line 826 ⟶ 1,298:
 
})();
</syntaxhighlight>
</lang>
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]</langsyntaxhighlight>
 
 
Functions of arbitrary arity can also be curried:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// (arbitrary arity to fully curried)
Line 867 ⟶ 1,339:
// [14, 28, 42, 56, 70, 84, 98, 112, 126, 140]
 
})();</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[14, 28, 42, 56, 70, 84, 98, 112, 126, 140]</langsyntaxhighlight>
 
===ES6===
 
====Y combinator====
Using a definition of currying that does not imply partial application, only conversion of a function of multiple arguments, e.g.: <langsyntaxhighlight lang="javascript">(a,b) => expr_using_a_and_b</langsyntaxhighlight>into a function that takes a series of as many function applications as that function took arguments, e.g.:<langsyntaxhighlight lang="javascript">a => b => expr_using_a_and_b</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="javascript">let
fix = // This is a variant of the Applicative order Y combinator
f => (f => f(f))(g => f((...a) => g(g)(...a))),
Line 901 ⟶ 1,373:
print(curriedmax(8)(4),curryrestedmax(8)(4)(),curryrestedmax(8)(4)(9,7,2));
// 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.
 
Line 908 ⟶ 1,380:
In the most rudimentary form, for example for mapping a two-argument function over an array:
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// curry :: ((a, b) -> c) -> a -> b -> c
Line 934 ⟶ 1,406:
// [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
 
})();</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]</langsyntaxhighlight>
 
 
Or, recursively currying functions of arbitrary arity:
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// (arbitrary arity to fully curried)
Line 970 ⟶ 1,442:
// [14, 28, 42, 56, 70, 84, 98, 112, 126, 140]
 
})();</langsyntaxhighlight>
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[14, 28, 42, 56, 70, 84, 98, 112, 126, 140]</langsyntaxhighlight>
 
=={{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):
<langsyntaxhighlight lang="jq">
def plus(x): . + x;
 
def plus5: plus(5);
</syntaxhighlight>
</lang>
 
We can now use plus5 as a filter, e.g.<syntaxhighlight lang ="jq">3 | plus5</langsyntaxhighlight> produces 8.
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
function addN(n::Number)::Function
adder(x::Number) = n + x
return adder
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,003 ⟶ 1,475:
 
</pre>
 
A shorter form of the above function, also without type specification:
<syntaxhighlight lang="julia">
addN(n) = x -> n + x
</syntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun curriedAdd(x: Int) = { y: Int -> x + y }
Line 1,014 ⟶ 1,491:
val sum = curriedAdd(a)(b)
println("$a + $b = $sum")
}</langsyntaxhighlight>
 
{{out}}
Line 1,023 ⟶ 1,500:
=={{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.
<langsyntaxhighlight lang="scheme">
1) just define function a binary function:
{def power {lambda {:a :b} {pow :a :b}}}
Line 1,037 ⟶ 1,514:
{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
</syntaxhighlight>
</lang>
 
=={{header|Latitude}}==
 
<syntaxhighlight lang="text">addN := {
takes '[n].
{
Line 1,049 ⟶ 1,526:
 
add3 := addN 3.
add3 (4). ;; 7</langsyntaxhighlight>
 
Note that, because of the syntax of the language, it is not possible to call <code>addN</code> in one line the naive way.
<langsyntaxhighlight lang="latitude">;; addN (3) (4). ;; Syntax error!
;; (addN (3)) (4). ;; Syntax error!
addN (3) call (4). ;; Works as expected.</langsyntaxhighlight>
 
As a consequence, it is more common in Latitude to return new objects whose methods have meaningful names, rather than returning a curried function.
<langsyntaxhighlight lang="latitude">addN := {
takes '[n].
Object clone tap {
Line 1,066 ⟶ 1,543:
}.
 
addN 3 do 4. ;; 7</langsyntaxhighlight>
 
=={{header|LFE}}==
<langsyntaxhighlight lang="lisp">(defun curry (f arg)
(lambda (x)
(apply f
(list arg x))))
</syntaxhighlight>
</lang>
Usage:
<langsyntaxhighlight lang="lisp">
(funcall (curry #'+/2 10) 10)
</syntaxhighlight>
</lang>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">
| ?- logtalk << call([Z]>>(call([X,Y]>>(Y is X*X), 5, R), Z is R*R), T).
T = 625
yes
</syntaxhighlight>
</lang>
 
Logtalk support for lambda expressions and currying was introduced in version 2.38.0, released in December 2009.
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
function curry2(f)
return function(x)
Line 1,107 ⟶ 1,584:
assert(add2(3) == 2+3)
assert(add2(5) == 2+5)
</syntaxhighlight>
</lang>
=== another implementation ===
Proper currying, tail call without array packing/unpack.
<langsyntaxhighlight lang="lua">
local curry do
local call,env = function(fn,...)return fn(...)end
local fmt,cat,rawset,rawget,floor = string.format,table.concat,rawset,rawget,math.floor
local curryHelper = setmetatable({},{
Line 1,122 ⟶ 1,599:
s = n<m and fmt('CALL(%s)',r) or fmt('function(...)return ME(%d,%d+select("#",...),%s)end',n,m,s)
local sc = fmt('local %s=... return %s',r,s)
rawset(me,k,(loadstring or load)(sc,'_',nil,{CALL=call,ME=me,select=select}env) )
return rawget(me,k)
end})
env = {CALL=call,ME=curryHelper,select=select}
function curry(...)
local pn,n,fn = select('#',...),...
Line 1,145 ⟶ 1,623:
assert(add2(3) == 2+3)
assert(add2(5) == 2+5)
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module LikeCppLikeGroovy {
divide=lambda (x, y)->x/y
partsof120=lambda divide ->divide(120, ![], 120)
Print "half of 120 is ";partsof120(2)
Print "a third is ";partsof120(3)
Print "and a quarter is ";partsof120(4)
}
LikeGroovy
LikeCpp
 
Module Joke {
Line 1,191 ⟶ 1,669:
}
Joke
</syntaxhighlight>
</lang>
Without joke, can anyone answer this puzzle?
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Puzzle {
Global Group F2 {
Line 1,220 ⟶ 1,698:
}
Puzzle
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Line 1,243 ⟶ 1,721:
Out[5]:= 5
</pre>
 
=={{header|MiniScript}}==
{{trans|Rust}}
<syntaxhighlight lang="miniscript">addN = function(n)
f = function(x)
return n + x
end function
return @f
end function
 
adder = addN(40)
print "The answer to life is " + adder(2) + "."</syntaxhighlight>
 
{{out}}
<pre>The answer to life is 42.</pre>
 
=={{header|Nemerle}}==
Currying isn't built in to Nemerle, but is relatively straightforward to define.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
Line 1,265 ⟶ 1,758:
WriteLine($"$(h(30))")
}
}</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc addN[T](n: T): auto = (proc(x: T): T = x + n)
 
let add2 = addN(2)
echo add2(7)</langsyntaxhighlight>
Alternative syntax:
<langsyntaxhighlight lang="nim">import futuresugar
 
proc addM[T](n: T): auto = (x: T) => x + n
 
let add3 = addM(3)
echo add3(7)</langsyntaxhighlight>
 
=={{header|OCaml}}==
OCaml has a built-in natural method of defining functions that are curried:
<langsyntaxhighlight lang="ocaml">let addnums x y = x+y (* declare a curried function *)
 
let add1 = addnums 1 (* bind the first argument to get another function *)
add1 42 (* apply to actually compute a result, 43 *)</langsyntaxhighlight>
The type of <code>addnums</code> above will be <tt>int -> int -> int</tt>.
 
Line 1,291 ⟶ 1,784:
 
You can also define a general currying higher-ordered function:
<langsyntaxhighlight lang="ocaml">let curry f x y = f (x,y)
(* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *)</langsyntaxhighlight>
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}}==
 
<langsyntaxhighlight Oforthlang="oforth">2 #+ curry => 2+
5 2+ .
7 ok</langsyntaxhighlight>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (addN n)
(lambda (x) (+ x n)))
Line 1,310 ⟶ 1,803:
(print "(add10 4) ==> " (add10 4))
(print "(add20 4) ==> " (add20 4)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,319 ⟶ 1,812:
=={{header|PARI/GP}}==
Simple currying example with closures.
<langsyntaxhighlight lang="parigp">curriedPlus(x)=y->x+y;
curriedPlus(1)(2)</langsyntaxhighlight>
{{out}}
<pre>3</pre>
Line 1,326 ⟶ 1,819:
=={{header|Perl}}==
This is a [[Perl|Perl 5]] example of a general curry function and curried plus using [[wp:closure (computer science)|closures]]:
<langsyntaxhighlight lang="perl">sub curry{
my ($func, @args) = @_;
 
Line 1,340 ⟶ 1,833:
 
my $plusXOne = curry(\&plusXY, 1);
print &$plusXOne(3), "\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
Phix does not support currying. The closest I can manage is very similar to my solution for closures
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence curries = {}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
function create_curried(integer rid, sequence partial_args)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">curries</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
curries = append(curries,{rid,partial_args})
<span style="color: #008080;">function</span> <span style="color: #000000;">create_curried</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">partial_args</span><span style="color: #0000FF;">)</span>
return length(curries) -- (return an integer id)
<span style="color: #000000;">curries</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curries</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span><span style="color: #000000;">partial_args</span><span style="color: #0000FF;">})</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curries</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (return an integer id)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function call_curried(integer id, sequence args)
{integer rid, sequence partial_args} = curries[id]
<span style="color: #008080;">function</span> <span style="color: #000000;">call_curried</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">id</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">args</span><span style="color: #0000FF;">)</span>
return call_func(rid,partial_args&args)
<span style="color: #0000FF;">{</span><span style="color: #004080;">integer</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">partial_args</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">curries</span><span style="color: #0000FF;">[</span><span style="color: #000000;">id</span><span style="color: #0000FF;">]</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">call_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span><span style="color: #000000;">partial_args</span><span style="color: #0000FF;">&</span><span style="color: #000000;">args</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function add(atom a, b)
return a+b
<span style="color: #008080;">function</span> <span style="color: #000000;">add</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">+</span><span style="color: #000000;">b</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
integer curried = create_curried(routine_id("add"),{2})
printf(1,"2+5=%d\n",call_curried(curried,{5}))</lang>
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,368 ⟶ 1,864:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
 
function curry($callable)
Line 1,462 ⟶ 1,958:
}
 
echo json_encode(array_map(curry('product', 7), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));</langsyntaxhighlight>
{{out}}<pre>[7,14,21,28,35,42,49,56,63,70]</pre>
 
Line 1,475 ⟶ 1,971:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Add($x) { return { param($y) return $y + $x }.GetNewClosure() }
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
& (Add 1) 2
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,486 ⟶ 1,982:
</pre>
Add each number in list to its square root:
<syntaxhighlight lang="powershell">
<lang PowerShell>
(4,9,16,25 | ForEach-Object { & (add $_) ([Math]::Sqrt($_)) }) -join ", "
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,511 ⟶ 2,007:
===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:
<langsyntaxhighlight lang="python"> def addN(n):
def adder(x):
return x + n
return adder</langsyntaxhighlight>
 
<langsyntaxhighlight lang="python"> >>> add2 = addN(2)
>>> add2
<function adder at 0x009F1E30>
>>> add2(7)
9</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="python">>>> from functools import partial
>>> from operator import add
>>> add2 = partial(add, 2)
Line 1,532 ⟶ 2,028:
>>> double = partial(map, lambda x: x*2)
>>> print(*double(range(5)))
0 2 4 6 8</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="python">>>> from toolz import curry
>>> import operator
>>> add = curry(operator.add)
Line 1,547 ⟶ 2,043:
>>> double = map(lambda x: x*2)
>>> print(*double(range(5)))
0 2 4 6 8</langsyntaxhighlight>
 
===Automatic curry and uncurry functions using lambdas===
Line 1,554 ⟶ 2,050:
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'':
 
<langsyntaxhighlight lang="python"># AUTOMATIC CURRYING AND UNCURRYING OF EXISTING FUNCTIONS
 
 
Line 1,607 ⟶ 2,103:
 
 
main()</langsyntaxhighlight>
{{Out}}
<pre>Manually curried using a lambda:
Line 1,627 ⟶ 2,123:
100
1000 </pre>
 
=={{header|Quackery}}==
 
Quackery does not have a currying function, but one is easily defined.
 
The word <code>curried</code> in the definition below curries the word following it, (which should act on two arguments on the stack), with the argument on the top of the stack. In the shell dialogue in the '''output:''' section the word <code>+</code> is combined with the number <code>5</code> on the top of stack to create the curried lambda nest <code>[ ' 5 + ]</code> which will add 5 the number on the top of stack when it is evaluated with <code>do</code>.
 
In the second example we drop the 8 from the previous example from the stack and then use currying to join "lamb" to "balti".
 
<syntaxhighlight lang="quackery"> [ ' [ ' ] swap nested join
]'[ nested join ] is curried ( x --> [ )</syntaxhighlight>
 
{{out}}
 
<pre>/O> 5 curried +
...
 
Stack: [ ' 5 + ]
 
/O> 3 swap do
...
 
Stack: 8
 
/O> drop
... $ "balti" curried join
... $ "lamb " swap do echo$
...
lamb balti
Stack empty.
</pre>
 
 
=={{header|R}}==
{{works with|R|4.1.0}}
 
We can easily define ''currying'' and ''uncurrying'' for two-argument functions as follows:
 
<syntaxhighlight lang="rsplus">
curry <- \(f) \(x) \(y) f(x, y)
uncurry <- \(f) \(x, y) f(x)(y)
</syntaxhighlight>
 
Here are some examples
 
<syntaxhighlight lang="rsplus">
add_curry <- curry(`+`)
add2 <- add_curry(2)
add2(40)
uncurry(add_curry)(40, 2)
</syntaxhighlight>
 
{{out}}
<pre>
> curry <- \(f) \(x) \(y) f(x, y)
> uncurry <- \(f) \(x, y) f(x)(y)
>
> add_curry <- curry(`+`)
> add2 <- add_curry(2)
> add2(40)
[1] 42
> uncurry(add_curry)(40, 2)
[1] 42
</pre>
 
=={{header|Racket}}==
The simplest way to make a curried functions is to use curry:
 
<langsyntaxhighlight lang="racket">
#lang racket
(((curry +) 3) 2) ; =>5
</syntaxhighlight>
</lang>
 
As an alternative, one can use the following syntax:
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 1,644 ⟶ 2,204:
 
((curried+ 3) 2) ; => 5
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(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.
<syntaxhighlight lang="raku" perl6line>my &negative = &infix:<->.assuming(0);
say negative 1;</langsyntaxhighlight>
{{out}}
<pre>-1</pre>
Line 1,657 ⟶ 2,217:
This example is modeled after the &nbsp; '''D''' &nbsp; example.
===specific version===
<langsyntaxhighlight resslang="rexx">/*REXX program demonstrates a REXX currying method to perform addition. */
say 'add 2 to 3: ' add(2, 3)
say 'add 2 to 3 (curried):' add2(3)
Line 1,663 ⟶ 2,223:
/*──────────────────────────────────────────────────────────────────────────────────────*/
add: procedure; $= arg(1); do j=2 to arg(); $= $ + arg(j); end; return $
add2: procedure; return add( arg(1), 2)</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the defaults:}}
<pre>
Line 1,671 ⟶ 2,231:
 
===generic version===
<langsyntaxhighlight 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 (curried):' add2(3)
Line 1,682 ⟶ 2,242:
return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
add2: procedure; return add( arg(1), 2)</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
=={{header|RPL}}==
RPL has not been designed as a functional programming language, but appropriate words can be created so that it becomes almost one.
For RPL, all programs are functions that can take arguments (or not) from the stack. Programs can easily be converted into strings: it is then possible to have a program rewrite another one, in order to insert the desired argument in the code, thus avoiding to pick it in the stack.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ 2 OVER SIZE 1 - SUB
≫ ''''SHAVE'''' STO
→STR '''SHAVE'''
"≪" ROT →STR
IF LAST TYPE 6 == THEN '''SHAVE''' END +
" SWAP " + SWAP + STR→
≫ ''''CURRX'''' STO
→STR '''SHAVE'''
"≪" ROT →STR
IF LAST TYPE 6 == THEN '''SHAVE''' END +
SWAP + STR→
≫ ''''CURRY'''' STO
|
'''SHAVE''' ''( "abcde" -- "bcd" )''
'''CURRX''' ''( a ≪( x y -- z )≫ -- ≪( a y -- z )≫ )''
convert function to string and remove delimiters
rewrite the program beginning
if a is an object name, remove its delimiters
add a SWAP instruction to put a at stack level 2
'''CURRY''' ''( a ≪( x y -- z )≫ -- ≪( x a -- z )≫ )''
convert function to string and remove delimiters
rewrite the program beginning
if a is an object name, remove its delimiters
put the call to a at level 1
|}
Let's demonstrate the curryfication on the following function :
≪ SQ SWAP SQ SWAP - ≫
which calculates <code>x² - y²</code> on x and y passed as arguments resp. in levels 2 and 1 of the stack. The following sequence of instructions:
5 ≪ SQ SWAP SQ SWAP - ≫ '''CURRX''' 'D2SQY' STO
returns a curryfied program stored as the word <code>D2SQY</code>. We can then check it works as planned:
'Y' D2SQY
will return
1: '25-SQ(Y)'
Similarly:
5 ≪ SQ SWAP SQ SWAP - ≫ '''CURRY''' 'D2SQX' STO
will return a new program named <code>D2SQX</code>, which effect on the 'X' argument at stack level 1 will be:
1: 'SQ(X)-25'
It is also possible to pass the reference to the function to be curryfied, rather than the function itself. if <code>≪ SQ SWAP SQ SWAP - ≫</code> is stored as <code>D2SQ</code>, the following command line will have the same effect as above:
5 'D2SQ' '''CURRY''' 'D2SQX' STO
 
=={{header|Ruby}}==
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).
<langsyntaxhighlight lang="ruby">
b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
p b.curry[1][2][3] #=> 6
Line 1,702 ⟶ 2,320:
p b.curry(5)[1, 2][3, 4][5] #=> 15
p b.curry(1)[1] #=> 1
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
 
This is a simple currying function written in [[Rust]]:
<langsyntaxhighlight lang="rust">fn add_n(n : i32) -> impl Fn(i32) -> i32 {
move |x| n + x
}
Line 1,714 ⟶ 2,332:
let adder = add_n(40);
println!("The answer to life is {}.", adder(2));
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">
<lang Scala>
def add(a: Int)(b: Int) = a + b
val add5 = add(5) _
add5(2)
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
This can be done by using lazy methods:
<langsyntaxhighlight lang="ruby">var adder = 1.method(:add);
say adder(3); #=> 4</langsyntaxhighlight>
 
Or by using a generic curry function:
<langsyntaxhighlight lang="ruby">func curry(f, *args1) {
func (*args2) {
f(args1..., args2...);
Line 1,740 ⟶ 2,358:
 
var adder = curry(add, 1);
say adder(3); #=>4</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Standard ML has a built-in natural method of defining functions that are curried:
<langsyntaxhighlight 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 *)
add1 42 (* apply to actually compute a result, 43 *)</langsyntaxhighlight>
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,753 ⟶ 2,371:
 
You can also define a general currying higher-ordered function:
<langsyntaxhighlight lang="sml">fun curry f x y = f(x,y)
(* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *)</langsyntaxhighlight>
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}}==
You can return a closure (or nested function):
<langsyntaxhighlight Swiftlang="swift">func addN(n:Int)->Int->Int { return {$0 + n} }
 
var add2 = addN(2)
println(add2) // (Function)
println(add2(7)) // 9</langsyntaxhighlight>
 
Prior to Swift 3, there was a curried function definition syntax:
<langsyntaxhighlight Swiftlang="swift">func addN(n:Int)(x:Int) -> Int { return x + n }
 
var add2 = addN(2)
println(add2) // (Function)
println(add2(x:7)) // 9</langsyntaxhighlight>
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:
<langsyntaxhighlight Swiftlang="swift">func addN(n:Int)(_ x:Int) -> Int { return x + n }
 
var add2 = addN(2)
println(add2) // (Function)
println(add2(7)) // 9</langsyntaxhighlight>
 
=={{header|Tcl}}==
The simplest way to do currying in Tcl is via an interpreter alias:
<langsyntaxhighlight lang="tcl">interp alias {} addone {} ::tcl::mathop::+ 1
puts [addone 6]; # => 7</langsyntaxhighlight>
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===
Line 1,800 ⟶ 2,418:
A two-argument function which subtracts is arguments from 10, and then subtracts five:
 
<langsyntaxhighlight lang="txrlisp">(op - 10 @1 @2 5)</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="txrlisp">(defun g (x)
(lambda (y)
(lambda (z)
(* (+ x y) z))))</langsyntaxhighlight>
 
Or, by referring to the definition of <code>f</code>:
 
<langsyntaxhighlight lang="txrlisp">(defun g (x)
(lambda (y)
(lambda (z)
(f x y z))))</langsyntaxhighlight>
 
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|Visual Basic .NETVala}}==
<syntaxhighlight lang="vala">delegate double Dbl_Op(double d);
'''Compiler:''' Roslyn Visual Basic (language version >=15.3)
 
Dbl_Op curried_add(double a) {
Functions are not curried in VB.NET, so this entry details functions that take a function and return functions that act as if the original function were curried (i.e. each takes one parameter and returns another function that takes one parameter, with the function for which all parameters of the original function are supplied calling the original function with those arguments.
return (b) => a + b;
}
 
void main() {
===Fixed-arity approach===
print(@"$(curried_add(3.0)(4.0))\n");
 
double sum2 = curried_add(2.0) (curried_add(3.0)(4.0)); //sum2 = 9
Uses generics and lambdas returning lambdas.
print(@"$sum2\n");
 
}</syntaxhighlight>
<lang vbnet>Option Explicit On
{{out}}
Option Infer On
<pre>
Option Strict On
7
 
9
Module Currying
</pre>
' The trivial curry.
Function Curry(Of T1, TResult)(func As Func(Of T1, TResult)) As Func(Of T1, TResult)
' At least satisfy the implicit contract that the result isn't reference-equal to the original function.
Return Function(a) func(a)
End Function
 
Function Curry(Of T1, T2, TResult)(func As Func(Of T1, T2, TResult)) As Func(Of T1, Func(Of T2, TResult))
Return Function(a) Function(b) func(a, b)
End Function
 
Function Curry(Of T1, T2, T3, TResult)(func As Func(Of T1, T2, T3, TResult)) As Func(Of T1, Func(Of T2, Func(Of T3, TResult)))
Return Function(a) Function(b) Function(c) func(a, b, c)
End Function
 
' And so on.
End Module</lang>
 
Test code:
<lang vbnet>Module Main
' An example binary function.
Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
 
Sub Main()
Dim curriedAdd = Curry(Of Integer, Integer, Integer)(AddressOf Add)
Dim add2To = curriedAdd(2)
 
Console.WriteLine(Add(2, 3))
Console.WriteLine(add2To(3))
Console.WriteLine(curriedAdd(2)(3))
 
' An example ternary function.
Dim substring = Function(s As String, startIndex As Integer, length As Integer) s.Substring(startIndex, length)
Dim curriedSubstring = Curry(substring)
 
Console.WriteLine(substring("abcdefg", 2, 3))
Console.WriteLine(curriedSubstring("abcdefg")(2)(3))
 
' The above is just syntax sugar for this (a call to the Invoke() method of System.Delegate):
Console.WriteLine(curriedSubstring.Invoke("abcdefg").Invoke(2).Invoke(3))
 
Dim substringStartingAt1 = curriedSubstring("abcdefg")(1)
Console.WriteLine(substringStartingAt1(2))
Console.WriteLine(substringStartingAt1(4))
End Sub
End Module</lang>
 
===Late-binding approach===
 
{{libheader|.NET Core|2=>=1.0}}
or both
{{libheader|.NET Framework|2=>=4.5}}
and
{{libheader|System.Collections.Immutable|1.5.0}}
 
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
Option Infer On
Option Strict On
 
Module CurryingDynamic
' Cheat visual basic's syntax by defining a type that can be the receiver of what appears to be a method call.
' Needless to say, this is not idiomatic VB.
Class CurryDelegate
ReadOnly Property Value As Object
ReadOnly Property Target As [Delegate]
 
Sub New(value As Object)
Dim curry = TryCast(value, CurryDelegate)
If curry IsNot Nothing Then
Me.Value = curry.Value
Me.Target = curry.Target
ElseIf TypeOf value Is [Delegate] Then
Me.Target = DirectCast(value, [Delegate])
Else
Me.Value = value
End If
End Sub
 
' CurryDelegate could also work as a dynamic n-ary function delegate, if an additional ParamArray argument were to be added.
Default ReadOnly Property Invoke(arg As Object) As CurryDelegate
Get
If Me.Target Is Nothing Then Throw New InvalidOperationException("All curried parameters have already been supplied")
 
Return New CurryDelegate(Me.Target.DynamicInvoke({arg}))
End Get
End Property
 
' A syntactically natural way to assert that the currying is complete and that the result is of the specified type.
Function Unwrap(Of T)() As T
If Me.Target IsNot Nothing Then Throw New InvalidOperationException("Some curried parameters have not yet been supplied.")
Return DirectCast(Me.Value, T)
End Function
End Class
 
Function DynamicCurry(func As [Delegate]) As CurryDelegate
Return DynamicCurry(func, ImmutableList(Of Object).Empty)
End Function
 
' Use ImmutableList to create a new list every time any curried subfunction is called avoiding multiple or repeated
' calls interfering with each other.
Private Function DynamicCurry(func As [Delegate], collectedArgs As ImmutableList(Of Object)) As CurryDelegate
Return If(collectedArgs.Count = func.Method.GetParameters().Length,
New CurryDelegate(func.DynamicInvoke(collectedArgs.ToArray())),
New CurryDelegate(Function(arg As Object) DynamicCurry(func, collectedArgs.Add(arg))))
End Function
End Module</lang>
 
Test code:
<lang vbnet>Module Program
Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
 
Sub Main()
' A delegate for the function must be created in order to eagerly perform overload resolution.
Dim curriedAdd = DynamicCurry(New Func(Of Integer, Integer, Integer)(AddressOf Add))
Dim add2To = curriedAdd(2)
 
Console.WriteLine(add2To(3).Unwrap(Of Integer))
Console.WriteLine(curriedAdd(2)(3).Unwrap(Of Integer))
 
Dim substring = Function(s As String, i1 As Integer, i2 As Integer) s.Substring(i1, i2)
Dim curriedSubstring = DynamicCurry(substring)
 
Console.WriteLine(substring("abcdefg", 2, 3))
Console.WriteLine(curriedSubstring("abcdefg")(2)(3).Unwrap(Of String))
 
' The trickery of using a parameterized default property also makes it appear that the "delegate" has an Invoke() method.
Console.WriteLine(curriedSubstring.Invoke("abcdefg").Invoke(2).Invoke(3).Unwrap(Of String))
 
Dim substringStartingAt1 = curriedSubstring("abcdefg")(1)
Console.WriteLine(substringStartingAt1(2).Unwrap(Of String))
Console.WriteLine(substringStartingAt1(4).Unwrap(Of String))
End Sub
End Module
</lang>
 
{{out|note=for both versions}}
<pre>5
5
5
cde
cde
cde
bc
bcde</pre>
 
=={{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.
<langsyntaxhighlight lang="wortel">@let {
addOne \+ 1
subtractFrom1 \- 1
Line 2,003 ⟶ 2,475:
!addOne_2 5 ; returns 6
]]
}</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|Rust}}
<langsyntaxhighlight ecmascriptlang="wren">var addN = Fn.new { |n| Fn.new { |x| n + x } }
 
var adder = addN.call(40)
System.print("The answer to life is %(adder.call(2)).")</langsyntaxhighlight>
 
{{out}}
Line 2,016 ⟶ 2,488:
The answer to life is 42.
</pre>
 
=={{header|Z80 Assembly}}==
{{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.
<syntaxhighlight lang="z80">macro ResetCursors
ld hl,&0101
call &BB75
endm</syntaxhighlight>
 
=={{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.
<langsyntaxhighlight 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
// fix first and third parameters:
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
f:=fcn(f,x){f(x)+x}.fp(fcn(x){x+1}); // above with lambdas all the way down</langsyntaxhighlight>
56

edits