Currying: Difference between revisions

From Rosetta Code
Content added Content deleted
(GP)
(→‎{{header|Perl 6}}: make work again)
Line 307: Line 307:


=={{header|Perl 6}}==
=={{header|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.
{{incorrect}}
All callable objects have a "assuming" method.
<lang perl6>my &negative = &infix:<->.assuming(0);
say negative 1;</lang>
<lang perl6>sub f($a, $b) { $a - $b }
say .(1) for &f.assuming(0), &f.assuming(*, 0)</lang>
{{out}}
{{out}}
<pre>-1
<pre>-1</pre>
1</pre>


=={{header|Prolog}}==
=={{header|Prolog}}==

Revision as of 22:42, 21 February 2014

This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Currying is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Create a simple demonstrative example of Currying in the specific language.

Add any historic details as to how the feature made its way into the language.

ALGOL 68

In 1968 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 #

MODE FUN = PROC (REAL) REAL; PROC pow = (FUN f, INT n, REAL x) REAL: f(x) ** n; OP ** = (FUN f, INT n) FUN: pow (f, n, );

  1. Example: sin (3 x) = 3 sin (x) - 4 sin^3 (x) (follows from DeMoivre's theorem) #

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

C#

This shows how to create syntactically natural currying functions in C#. <lang csharp>public delegate int Plus(int y); public delegate Plus CurriedPlus(int x); public static CurriedPlus plus =

     delegate(int x) {return delegate(int y) {return x + y;};};

static void Main() {

   int sum = plus(3)(4); // sum = 7
   int sum2= plus(2)(plus(3)(4)) // sum2 = 9

}</lang>

C++

Currying may be achieved in C++ using the Standard Template Library function object adapters (binder1st and binder2nd), and more generically using the Boost bind mechanism.

Common Lisp

<lang lisp>(defun curry (function &rest args-1)

 (lambda (&rest args-2)
   (apply function (append args-1 args-2))))

</lang>

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

20 </lang>

D

<lang d>void main() {

   import std.stdio, std.functional;
   int add(int a, int b) {
       return a + b;
   }
   alias add2 = curry!(add, 2);
   writeln("Add 2 to 3: ", add(2, 3));
   writeln("Add 2 to 3 (curried): ", add2(3));

}</lang>

Output:
Add 2 to 3: 5
Add 2 to 3 (curried): 5

Eero

<lang objc>#import <stdio.h>

int main()

 addN := (int n)
   int adder(int x)
     return x + n
   return adder
 add2 := addN(2)
 printf( "Result = %d\n", add2(7) )
 return 0

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

int main()

 addN := (int n)
   return (int x | return x + n)
 add2 := addN(2)
 printf( "Result = %d\n", add2(7) )
 return 0

</lang>

Eiffel

Eiffel has direct support for lambda expressions and hence currying through "inline agents". If f is a function with two arguments, of signature (X × Y) → Z then its curried version is obtained by simply writing

   g (x: X): FUNCTION [ANY, TUPLE [Y], Z]
       do
           Result := agent (closed_x: X; y: Y): Z 
              do 
                 Result := f (closed_x, y) 
              end (x, ?)
       end

where FUNCTION [ANY, TUPLE [Y], Z] denotes the type YZ (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.

F#

Translation of: Python

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

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

val add2 : (int -> int)

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

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)

   Prelude> let plus = \x y -> x + y
   Prelude> :type plus
   plus :: Integer -> Integer -> Integer
   Prelude> plus 3 5
   8

and currying functions is trivial

   Prelude> let plus5 = plus 5
   Prelude> :type plus5
   plus5 :: Integer -> Integer
   Prelude> plus5 3
   8

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

   Prelude> let nested_plus = \x -> \y -> x + y
   Prelude> :type nested_plus
   nested_plus :: Integer -> Integer -> Integer

Io

A general currying function written in the Io programming language: <lang io>curry := method(fn, a := call evalArgs slice(1) block( b := a clone appendSeq(call evalArgs) performWithArgList("fn", b) ) )

// example: increment := curry( method(a,b,a+b), 1 ) increment call(5) // result => 6</lang>

J

Solution:Use & (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&+

  threePlus 7

10

  halve =: %&2  NB.  % means divide 
  halve 20

10

  someParabola =: _2 3 1 &p. NB. x^2 + 3x - 2</lang>

Note: The final example (someParabola) shows the single currying primitive (&) combined with J's array oriented nature, permits partial application of a function of any number of arguments.

Java

<lang java5> public class Currier<ARG1, ARG2, RET> {

       public interface CurriableFunctor<ARG1, ARG2, RET> {
           RET evaluate(ARG1 arg1, ARG2 arg2);
       }
   
       public interface CurriedFunctor<ARG2, RET> {
           RET evaluate(ARG2 arg);
       }
   
       final CurriableFunctor<ARG1, ARG2, RET> functor;
   
       public Currier(CurriableFunctor<ARG1, ARG2, RET> fn) { functor = fn; }
       
       public CurriedFunctor<ARG2, RET> curry(final ARG1 arg1) {
           return new CurriedFunctor<ARG2, RET>() {
               public RET evaluate(ARG2 arg2) {
                   return functor.evaluate(arg1, arg2);
               }
           };
       }
   
       public static void main(String[] args) {
           Currier.CurriableFunctor<Integer, Integer, Integer> add
               = new Currier.CurriableFunctor<Integer, Integer, Integer>() {
                   public Integer evaluate(Integer arg1, Integer arg2) {
                       return new Integer(arg1.intValue() + arg2.intValue());
                   }
           };
           
           Currier<Integer, Integer, Integer> currier
               = new Currier<Integer, Integer, Integer>(add);
           
           Currier.CurriedFunctor<Integer, Integer> add5
               = currier.curry(new Integer(5));
           
           System.out.println(add5.evaluate(new Integer(2)));
       }
   }</lang>

JavaScript

<lang javascript> function addN(n) {

   var curry = function(x) {
       return x + n;
   };
   return curry;
}
add2 = addN(2);
alert(add2);
alert(add2(7));</lang>

LFE

<lang lisp>(defun curry (f arg)

 (lambda (x)
   (apply f
     (list arg x))))

</lang> Usage: <lang lisp> (funcall (curry #'+/2 10) 10) </lang>

ML

This example is in need of improvement:

This example is alone in "ML" category. Should it appear under Standard ML or Ocaml?

Suppose that plus is a function taking two arguments x and y and returning x + y. In the ML programming language we would define it as follows:

   plus = fn(x, y) => x + y

and plus(1, 2) returns 3 as we expect.

The curried version of plus takes a single argument x and returns a new function which takes a single argument y and returns x + y. In ML we would define it as follows:

   curried_plus = fn(x) => fn(y) => x + y

and now when we call curried_plus(1) we get a new function that adds 1 to its argument:

   plus_one = curried_plus(1)

and now plus_one(2) returns 3 and plus_one(7) returns 8.

When declaring functions in the strictly-typed OCaml programming language, the type returned by a function shows the Curried form of the function. Typing the function into the OCaml interpreter displays the type immediately:

   # let plus x y = x + y ;;
   val plus : int -> int -> int = <fun>

Nemerle

Currying isn't built in to Nemerle, but is relatively straightforward to define. <lang Nemerle>using System; using System.Console;

module Curry {

   Curry[T, U, R](f : T * U -> R) : T -> U -> R
   {
       fun (x) { fun (y) { f(x, y) } }
   }

   Main() : void
   {
       def f(x, y) { x + y }

def g = Curry(f); def h = Curry(f)(12); // partial application WriteLine($"$(Curry(f)(20)(22))"); WriteLine($"$(g(21)(21))"); WriteLine($"$(h(30))")

   }

}</lang>

PARI/GP

Simple currying example with closures. <lang parigp>curriedPlus(x)=y->x+y; curriedPlus(1)(2)</lang>

Output:
3

Perl

This is a Perl 5 example of a general curry function and curried plus using closures: <lang perl>sub curry{

 my ($func, @args) = @_;
 sub {
   #This @_ is later
   &$func(@args, @_);
 }

}

sub plusXY{

 $_[0] + $_[1];

}

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

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. <lang perl6>my &negative = &infix:<->.assuming(0); say negative 1;</lang>

Output:
-1

Prolog

Works with SWI-Prolog and module lambda.pl
Module lambda.pl can be found at http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl .

 ?- [library('lambda.pl')].
% library(lambda.pl) compiled into lambda 0,00 sec, 28 clauses
true.

 ?- N = 5, F = \X^Y^(Y is X+N), maplist(F, [1,2,3], L).
N = 5,
F = \X^Y^ (Y is X+5),
L = [6,7,8].

Python

<lang python> def addN(n):

    def adder(x):
        return x + n
    return adder</lang>

<lang python> >>> add2 = addN(2)

>>> add2
<function adder at 0x009F1E30>
>>> add2(7)
9</lang>

Racket

The simplest way to make a curried functions is to use curry:

<lang racket>

  1. lang racket

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

As an alternative, one can use the following syntax: <lang racket>

  1. lang racket

(define ((curried+ a) b)

 (+ a b))

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

REXX

This example is modeled after the   D   example.

specific version

<lang ress>/*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) exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────subroutines─────────────────────────*/ add: procedure; $=arg(1); do j=2 to arg(); $=$+arg(j); end; return $ add2: procedure; return add(arg(1), 2)</lang> output

add 2 to 3:           5
add 2 to 3 (curried): 5

generic version

<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) exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────ADD subroutine──────────────────────*/ add: procedure; $=0; do j=1 for arg()

                           do k=1  for words(arg(j));  $=$+word(arg(j),k)
                           end   /*k*/
                        end      /*j*/

return $ /*──────────────────────────────────ADD2 subroutine─────────────────────*/ add2: procedure; return add(arg(1), 2)</lang> output is the same as the 1st version.

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). <lang ruby> b = proc {|x, y, z| (x||0) + (y||0) + (z||0) } p b.curry[1][2][3] #=> 6 p b.curry[1, 2][3, 4] #=> 6 p b.curry(5)[1][2][3][4][5] #=> 6 p b.curry(5)[1, 2][3, 4][5] #=> 6 p b.curry(1)[1] #=> 1

b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) } p b.curry[1][2][3] #=> 6 p b.curry[1, 2][3, 4] #=> 10 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 </lang>

Scheme

This is a simple general currying function written in Scheme: <lang scheme>;curry:function,args->(function)

Adding using currying

(define (curry f . args) (lambda x (apply f (append args x))))</lang> This is an example of applying a curried function: <lang scheme>>((curry + 10) 10) 20</lang>

Standard ML

Standard ML has a built-in natural method of defining functions that are curryable: <lang sml>fun addnums x:int y = x+y (* declare a curryable function *)

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

You can also define a general currying functor: <lang sml>fun curry f x y = f(x,y) (* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *)</lang> 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.

Tcl

The simplest way to do currying in Tcl is via an interpreter alias: <lang tcl>interp alias {} addone {} ::tcl::mathop::+ 1 puts [addone 6]; # => 7</lang> 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

The type of aliases used here are a simple restriction of general inter-interpreter aliases to the case where both the source and target interpreter are the current one; these aliases are a key component of the secure interpreter mechanism introduced in Tcl 7.6, and are the mechanism used to allow access to otherwise-insecure behavior from a secure context (e.g., to write to a particular file, but not any old file).

Wortel

The \ operator takes a function and an argument and partial applies the argument to the function. The &\ works like the \ operator but can also take an array literal and partial applies all the arguments in the array. <lang wortel>@let {

 addOne \+ 1
 subtractFrom1 \- 1
 subtract1 \~- 1
 
 subtract1_2 &\- [. 1]
 add ^+
 ; partial apply to named functions
 addOne_2 \add 1
 ; testing
 [[
   !addOne 5 ; returns 6
   !subtractFrom1 5 ; returns -4
   !subtract1 5 ; returns 4
   !subtract1_2 5 ; returns 4
   !addOne_2 5 ; returns 6
 ]]

}</lang>