Currying: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|R}}) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 14:
{{trans|Python}}
<
F adder(x)
R x + @=n
Line 22:
V add3 = addN(3)
print(add2(7))
print(add3(7))</
{{out}}
Line 34:
Support package spec:
<
type Argument_1 (<>) is limited private;
type Argument_2 (<>) is limited private;
Line 63:
end Apply_1;
end Curry_3;</
Support package body:
<
package body Apply_1 is
Line 83:
end Apply_1;
end Curry_3;</
Currying a function:
<
procedure Curry_Test is
Line 112:
Ada.Text_IO.Put_Line ("Five plus seven plus three is" & Integer'Image (Result));
end Curry_Test;</
Output:
Line 119:
=={{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:
<
{
l[0] = apply.apply(l[0]);
Line 132:
0;
}
</syntaxhighlight>
{{out}}
<pre> 000,040,000,000</pre>
Line 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]].
<
MODE FUN = PROC (REAL) REAL;
Line 147:
REAL x = read real;
print ((new line, sin (3 * x), 3 * sin (x) - 4 * (sin ** 3) (x)))</
=={{header|AppleScript}}==
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.
<
on curry(f)
script
Line 250:
end script
end if
end mReturn</
{{Out}}
<pre>{«script», «script», 5, {7, 14, 21, 28, 35, 42, 49, 56, 63, 70}}</pre>
Line 258:
Adapted from [[Currying#J|J]].
<
Plus3_1 ← +⟜3
•Show Plus3 1
•Show Plus3_1 1</
<syntaxhighlight lang="text">4
4</
=={{header|C}}==
<syntaxhighlight lang="c">
#include<stdarg.h>
#include<stdio.h>
Line 301:
return 0;
}
</syntaxhighlight>
Output:
<pre>
Line 313:
=={{header|C sharp|C#}}==
This shows how to create syntactically natural currying functions in [[C sharp|C#]].
<
public delegate Plus CurriedPlus(int x);
public static CurriedPlus plus =
Line 321:
int sum = plus(3)(4); // sum = 7
int sum2= plus(2)(plus(3)(4)) // sum2 = 9
}</
=={{header|C++}}==
Line 328:
=={{header|Ceylon}}==
{{trans|Groovy}}
<
function divide(Integer x, Integer y) => x / y;
Line 337:
a third is ``partsOf120(3)``
and a quarter is ``partsOf120(4)``");
}</
=={{header|Clojure}}==
<
(assert (=
(plus-a-hundred 1)
101))
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(lambda (&rest args-2)
(apply function (append args-1 args-2))))
</syntaxhighlight>
Usage:
<
(funcall (curry #'+ 10) 10)
20
</syntaxhighlight>
=={{header|Crystal}}==
Crystal allows currying procs with either <code>Proc#partial</code> or by manually creating closures:
<
add_curried = add_things.partial(2, 3)
add_curried.call(4) #=> 9
Line 372:
end
add13 = add_two_things(3).call(10)
add13.call(5) #=> 18</
=={{header|D}}==
<
import std.stdio, std.functional;
Line 385:
writeln("Add 2 to 3: ", add(2, 3));
writeln("Add 2 to 3 (curried): ", add2(3));
}</
{{out}}
<pre>Add 2 to 3: 5
Line 393:
{{libheader| System.SysUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Currying;
Line 420:
readln;
end.
</syntaxhighlight>
{{out}}
<pre>
Line 428:
=={{header|EchoLisp}}==
[[EchoLisp]] has native support for curry, which is implemented thru closures, as shown in [[CommonLisp]] .
<syntaxhighlight lang="text">
;;
;; curry functional definition
Line 448:
(curry * 2 3 (+ 2 2))
→ (λ _#:g1004 (#apply-curry #* (2 3 4) _#:g1004))
</syntaxhighlight>
=={{header|Eero}}==
<
int main()
Line 465:
return 0
</syntaxhighlight>
Alternative implementation (there are a few ways to express blocks/lambdas):
<
int main()
Line 479:
return 0
</syntaxhighlight>
=={{header|Eiffel}}==
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.
<
-module(currying).
Line 561:
erlang:error(badarg)
end.
</syntaxhighlight>
Line 601:
F# is largely based on ML and has a built-in natural method of defining functions that are curried:
<
<
val add2 : (int -> int)
Line 610:
val it : (int -> int) = <fun:addN@1>
> add2 7;;
val it : int = 9</
=={{header|Factor}}==
<
--- Data stack:
Line 620:
--- Data stack:
5</
Currying doesn't need to be an atomic operation. <tt>compose</tt> lets you combine quotations.
<
--- Data stack:
Line 630:
--- Data stack:
3
9</
You can even treat quotations as sequences.
<
--- Data stack:
{ 1 1+1/2 2 2+1/2 3 }</
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.
<
IN: scratchpad 2 3 '[ _ _ + ]
--- Data stack:
[ 2 3 + ]</
Use <tt>@</tt> to insert the contents of a quotation into another quotation.
<
--- Data stack:
{ 4 5 6 7 8 }</
=={{header|Forth}}==
{{trans|Common Lisp}}
<
swap 2>r :noname r> postpone literal r> compile, postpone ; ;
5 ' + curry constant +5
5 +5 execute .
7 +5 execute .</
{{out}}
Line 665:
=={{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:
<
Type CurriedAdd
Line 682:
Print "3 + 4 ="; add(3).add(4)
Print "2 + 6 ="; add(2).add(6)
Sleep</
{{out}}
Line 704:
[http://golang.org/ref/spec#Method_values Method values] were added
in [http://golang.org/doc/go1.1#method_values Go 1.1].
<
import (
Line 740:
fmt.Println("2 + 4 =", fn2(a, 4))
fmt.Println("3 + 5 =", fn2(Foo(3), 5))
}</
[http://play.golang.org/p/0YL9YTe-9V Run on the Go Playground.]
Line 748:
Example:
<
x / y
}
Line 754:
def partsOf120 = divide.curry(120)
println "120: half: ${partsOf120(2)}, third: ${partsOf120(3)}, quarter: ${partsOf120(4)}"</
Results:
Line 763:
Example (using the same "divide()" closure as before):
<
def third = divide.rcurry(3)
def quarter = divide.rcurry(4)
println "30: half: ${half(30)}; third: ${third(30)}, quarter: ${quarter(30)}"</
Results:
Line 776:
=={{header|Haskell}}==
Likewise in Haskell, function type signatures show the currying-based structure of functions (note: "<
Prelude> let plus = \x y -> x + y
Line 792:
8
In fact, the Haskell definition <
Prelude> let nested_plus = \x -> \y -> x + y
Line 799:
=={{header|Hy}}==
<
(fn [x]
(+ x n)))</
<
=> (add2 7)
9
=> ((addN 3) 4)
7</
==Icon and {{header|Unicon}}==
Line 814:
used.
<
add2 := addN(2)
write("add2(7) = ",add2(7))
Line 826:
procedure makeProc(A)
return (@A[1], A[1])
end</
{{Out}}
Line 838:
=={{header|Io}}==
A general currying function written in the [[Io]] programming language:
<
a := call evalArgs slice(1)
block(
Line 849:
increment := curry( method(a,b,a+b), 1 )
increment call(5)
// result => 6</
=={{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''':<
threePlus 7
10
Line 860:
halve 20
10
someParabola =: _2 3 1 &p. NB. x^2 + 3x - 2</
'''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:
'''Note''': J's adverbs and conjunctions (such as <code>&</code>) will curry themselves when necessary. Thus, for example:
<
+with2 3
5</
=={{header|Java}}==
<
public interface CurriableFunctor<ARG1, ARG2, RET> {
RET evaluate(ARG1 arg1, ARG2 arg2);
Line 908:
System.out.println(add5.evaluate(new Integer(2)));
}
}</
===Java 8===
<
import java.util.function.BiFunction;
import java.util.function.Function;
Line 947:
}
}
</syntaxhighlight>
=={{header|JavaScript}}==
Line 954:
====Partial application====
<
var curry = function(x) {
return x + n;
Line 963:
add2 = addN(2);
alert(add2);
alert(add2(7));</
====Generic currying====
Line 969:
Basic case - returning a curried version of a function of two arguments
<
// curry :: ((a, b) -> c) -> a -> b -> c
Line 1,003:
})();
</syntaxhighlight>
{{Out}}
<
Functions of arbitrary arity can also be curried:
<
// (arbitrary arity to fully curried)
Line 1,044:
// [14, 28, 42, 56, 70, 84, 98, 112, 126, 140]
})();</
{{Out}}
<
===ES6===
====Y combinator====
Using a definition of currying that does not imply partial application, only conversion of a function of multiple arguments, e.g.: <
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.
<
fix = // This is a variant of the Applicative order Y combinator
f => (f => f(f))(g => f((...a) => g(g)(...a))),
Line 1,078:
print(curriedmax(8)(4),curryrestedmax(8)(4)(),curryrestedmax(8)(4)(9,7,2));
// 8,8,9
</syntaxhighlight>
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:
In the most rudimentary form, for example for mapping a two-argument function over an array:
<
// curry :: ((a, b) -> c) -> a -> b -> c
Line 1,111:
// [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
})();</
{{Out}}
<
Or, recursively currying functions of arbitrary arity:
<
// (arbitrary arity to fully curried)
Line 1,147:
// [14, 28, 42, 56, 70, 84, 98, 112, 126, 140]
})();</
{{Out}}
<
=={{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):
<
def plus(x): . + x;
def plus5: plus(5);
</syntaxhighlight>
We can now use plus5 as a filter, e.g.<syntaxhighlight lang
=={{header|Julia}}==
<
function addN(n::Number)::Function
adder(x::Number) = n + x
return adder
end
</syntaxhighlight>
{{out}}
Line 1,182:
=={{header|Kotlin}}==
<
fun curriedAdd(x: Int) = { y: Int -> x + y }
Line 1,191:
val sum = curriedAdd(a)(b)
println("$a + $b = $sum")
}</
{{out}}
Line 1,200:
=={{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.
<
1) just define function a binary function:
{def power {lambda {:a :b} {pow :a :b}}}
Line 1,214:
{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>
=={{header|Latitude}}==
<syntaxhighlight lang="text">addN := {
takes '[n].
{
Line 1,226:
add3 := addN 3.
add3 (4). ;; 7</
Note that, because of the syntax of the language, it is not possible to call <code>addN</code> in one line the naive way.
<
;; (addN (3)) (4). ;; Syntax error!
addN (3) call (4). ;; Works as expected.</
As a consequence, it is more common in Latitude to return new objects whose methods have meaningful names, rather than returning a curried function.
<
takes '[n].
Object clone tap {
Line 1,243:
}.
addN 3 do 4. ;; 7</
=={{header|LFE}}==
<
(lambda (x)
(apply f
(list arg x))))
</syntaxhighlight>
Usage:
<
(funcall (curry #'+/2 10) 10)
</syntaxhighlight>
=={{header|Logtalk}}==
<
| ?- logtalk << call([Z]>>(call([X,Y]>>(Y is X*X), 5, R), Z is R*R), T).
T = 625
yes
</syntaxhighlight>
Logtalk support for lambda expressions and currying was introduced in version 2.38.0, released in December 2009.
=={{header|Lua}}==
<
function curry2(f)
return function(x)
Line 1,284:
assert(add2(3) == 2+3)
assert(add2(5) == 2+5)
</syntaxhighlight>
=== another implementation ===
Proper currying, tail call without array packing/unpack.
<
local curry do
local call,env = function(fn,...)return fn(...)end
Line 1,323:
assert(add2(3) == 2+3)
assert(add2(5) == 2+5)
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module LikeCpp {
divide=lambda (x, y)->x/y
Line 1,369:
}
Joke
</syntaxhighlight>
Without joke, can anyone answer this puzzle?
<syntaxhighlight lang="m2000 interpreter">
Module Puzzle {
Global Group F2 {
Line 1,398:
}
Puzzle
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Line 1,424:
=={{header|Nemerle}}==
Currying isn't built in to Nemerle, but is relatively straightforward to define.
<
using System.Console;
Line 1,443:
WriteLine($"$(h(30))")
}
}</
=={{header|Nim}}==
<
let add2 = addN(2)
echo add2(7)</
Alternative syntax:
<
proc addM[T](n: T): auto = (x: T) => x + n
let add3 = addM(3)
echo add3(7)</
=={{header|OCaml}}==
OCaml has a built-in natural method of defining functions that are curried:
<
let add1 = addnums 1 (* bind the first argument to get another function *)
add1 42 (* apply to actually compute a result, 43 *)</
The type of <code>addnums</code> above will be <tt>int -> int -> int</tt>.
Line 1,469:
You can also define a general currying higher-ordered function:
<
(* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *)</
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}}==
<
5 2+ .
7 ok</
=={{header|Ol}}==
<
(define (addN n)
(lambda (x) (+ x n)))
Line 1,488:
(print "(add10 4) ==> " (add10 4))
(print "(add20 4) ==> " (add20 4)))
</syntaxhighlight>
{{out}}
<pre>
Line 1,497:
=={{header|PARI/GP}}==
Simple currying example with closures.
<
curriedPlus(1)(2)</
{{out}}
<pre>3</pre>
Line 1,504:
=={{header|Perl}}==
This is a [[Perl|Perl 5]] example of a general curry function and curried plus using [[wp:closure (computer science)|closures]]:
<
my ($func, @args) = @_;
Line 1,518:
my $plusXOne = curry(\&plusXY, 1);
print &$plusXOne(3), "\n";</
=={{header|Phix}}==
Phix does not support currying. The closest I can manage is very similar to my solution for closures
<!--<
<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>
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: #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>
<!--</
{{out}}
<pre>
Line 1,549:
=={{header|PHP}}==
<
function curry($callable)
Line 1,643:
}
echo json_encode(array_map(curry('product', 7), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));</
{{out}}<pre>[7,14,21,28,35,42,49,56,63,70]</pre>
Line 1,656:
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function Add($x) { return { param($y) return $y + $x }.GetNewClosure() }
</syntaxhighlight>
<syntaxhighlight lang="powershell">
& (Add 1) 2
</syntaxhighlight>
{{Out}}
<pre>
Line 1,667:
</pre>
Add each number in list to its square root:
<syntaxhighlight lang="powershell">
(4,9,16,25 | ForEach-Object { & (add $_) ([Math]::Sqrt($_)) }) -join ", "
</syntaxhighlight>
{{Out}}
<pre>
Line 1,692:
===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:
<
def adder(x):
return x + n
return adder</
<
>>> add2
<function adder at 0x009F1E30>
>>> add2(7)
9</
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.
<
>>> from operator import add
>>> add2 = partial(add, 2)
Line 1,713:
>>> double = partial(map, lambda x: x*2)
>>> print(*double(range(5)))
0 2 4 6 8</
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:
<
>>> import operator
>>> add = curry(operator.add)
Line 1,728:
>>> double = map(lambda x: x*2)
>>> print(*double(range(5)))
0 2 4 6 8</
===Automatic curry and uncurry functions using lambdas===
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'':
<
Line 1,788:
main()</
{{Out}}
<pre>Manually curried using a lambda:
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".
<
]'[ nested join ] is curried ( x --> [ )</
{{out}}
Line 1,846:
We can easily define ''currying'' and ''uncurrying'' for two-argument functions as follows:
<
curry <- \(f) \(x) \(y) f(x, y)
uncurry <- \(f) \(x, y) f(x)(y)
</syntaxhighlight>
Here are some examples
<
add_curry <- curry(`+`)
add2 <- add_curry(2)
add2(40)
uncurry(add_curry)(40, 2)
</syntaxhighlight>
{{out}}
Line 1,876:
The simplest way to make a curried functions is to use curry:
<
#lang racket
(((curry +) 3) 2) ; =>5
</syntaxhighlight>
As an alternative, one can use the following syntax:
<
#lang racket
Line 1,889:
((curried+ 3) 2) ; => 5
</syntaxhighlight>
=={{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"
say negative 1;</
{{out}}
<pre>-1</pre>
Line 1,902:
This example is modeled after the '''D''' example.
===specific version===
<
say 'add 2 to 3: ' add(2, 3)
say 'add 2 to 3 (curried):' add2(3)
Line 1,908:
/*──────────────────────────────────────────────────────────────────────────────────────*/
add: procedure; $= arg(1); do j=2 to arg(); $= $ + arg(j); end; return $
add2: procedure; return add( arg(1), 2)</
{{out|output|text= when using the defaults:}}
<pre>
Line 1,916:
===generic version===
<
say 'add 2 to 3: ' add(2, 3)
say 'add 2 to 3 (curried):' add2(3)
Line 1,927:
return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
add2: procedure; return add( arg(1), 2)</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} <br><br>
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.
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).
<
b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
p b.curry[1][2][3] #=> 6
Line 1,947:
p b.curry(5)[1, 2][3, 4][5] #=> 15
p b.curry(1)[1] #=> 1
</syntaxhighlight>
=={{header|Rust}}==
This is a simple currying function written in [[Rust]]:
<
move |x| n + x
}
Line 1,959:
let adder = add_n(40);
println!("The answer to life is {}.", adder(2));
}</
=={{header|Scala}}==
<syntaxhighlight lang="scala">
def add(a: Int)(b: Int) = a + b
val add5 = add(5) _
add5(2)
</syntaxhighlight>
=={{header|Sidef}}==
This can be done by using lazy methods:
<
say adder(3); #=> 4</
Or by using a generic curry function:
<
func (*args2) {
f(args1..., args2...);
Line 1,985:
var adder = curry(add, 1);
say adder(3); #=>4</
=={{header|Standard ML}}==
Standard ML has a built-in natural method of defining functions that are curried:
<
val add1 = addnums 1 (* bind the first argument to get another function *)
add1 42 (* apply to actually compute a result, 43 *)</
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:
You can also define a general currying higher-ordered function:
<
(* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *)</
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):
<
var add2 = addN(2)
println(add2) // (Function)
println(add2(7)) // 9</
Prior to Swift 3, there was a curried function definition syntax:
<
var add2 = addN(2)
println(add2) // (Function)
println(add2(x:7)) // 9</
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:
<
var add2 = addN(2)
println(add2) // (Function)
println(add2(7)) // 9</
=={{header|Tcl}}==
The simplest way to do currying in Tcl is via an interpreter alias:
<
puts [addone 6]; # => 7</
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 2,045:
A two-argument function which subtracts is arguments from 10, and then subtracts five:
<
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:
<
(lambda (y)
(lambda (z)
(* (+ x y) z))))</
Or, by referring to the definition of <code>f</code>:
<
(lambda (y)
(lambda (z)
(f x y z))))</
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}}==
<
Dbl_Op curried_add(double a) {
Line 2,074:
double sum2 = curried_add(2.0) (curried_add(3.0)(4.0)); //sum2 = 9
print(@"$sum2\n");
}</
{{out}}
<pre>
Line 2,090:
Uses generics and lambdas returning lambdas.
<
Option Infer On
Option Strict On
Line 2,110:
' And so on.
End Module</
Test code:
<
' An example binary function.
Function Add(a As Integer, b As Integer) As Integer
Line 2,141:
Console.WriteLine(substringStartingAt1(4))
End Sub
End Module</
===Late-binding approach===
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.
<
Option Infer On
Option Strict On
Line 2,203:
New CurryDelegate(Function(arg As Object) DynamicCurry(func, collectedArgs.Add(arg))))
End Function
End Module</
Test code:
<
Function Add(a As Integer, b As Integer) As Integer
Return a + b
Line 2,233:
End Sub
End Module
</syntaxhighlight>
{{out|note=for both versions}}
Line 2,247:
=={{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.
<
addOne \+ 1
subtractFrom1 \- 1
Line 2,266:
!addOne_2 5 ; returns 6
]]
}</
=={{header|Wren}}==
{{trans|Rust}}
<
var adder = addN.call(40)
System.print("The answer to life is %(adder.call(2)).")</
{{out}}
Line 2,283:
{{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.
<
ld hl,&0101
call &BB75
endm</
=={{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.
<
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</
|