Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Currying

View file

@ -0,0 +1,8 @@
;Task:
Create a simple demonstrative example of [[wp:Currying|Currying]] in a specific language.
Add any historic details as to how the feature made its way into the language.
<!-- from: http://en.wikipedia.org/w/index.php?title=Currying&direction=prev&oldid=142127294 -->
[[Category:Functions and subroutines]]
<br><br>

View file

@ -0,0 +1,9 @@
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))

View file

@ -0,0 +1,10 @@
# 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, );
# 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)))

View file

@ -0,0 +1,30 @@
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;

View file

@ -0,0 +1,18 @@
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;

View file

@ -0,0 +1,27 @@
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;

View file

@ -0,0 +1,13 @@
ri(list l)
{
l[0] = apply.apply(l[0]);
}
curry(object o)
{
(o.__count - 1).times(ri, list(o));
}
main(void)
{
o_wbfxinteger.curry()(16)(3)(12)(16)(1 << 30);
0;
}

View file

@ -0,0 +1,98 @@
-- curry :: (Script|Handler) -> Script
on curry(f)
script
on |λ|(a)
script
on |λ|(b)
|λ|(a, b) of mReturn(f)
end |λ|
end script
end |λ|
end script
end curry
-- TESTS ----------------------------------------------------------------------
-- add :: Num -> Num -> Num
on add(a, b)
a + b
end add
-- product :: Num -> Num -> Num
on product(a, b)
a * b
end product
-- Test 1.
curry(add)
--> «script»
-- Test 2.
curry(add)'s |λ|(2)
--> «script»
-- Test 3.
curry(add)'s |λ|(2)'s |λ|(3)
--> 5
-- Test 4.
map(curry(product)'s |λ|(7), enumFromTo(1, 10))
--> {7, 14, 21, 28, 35, 42, 49, 56, 63, 70}
-- Combined:
{curry(add), ¬
curry(add)'s |λ|(2), ¬
curry(add)'s |λ|(2)'s |λ|(3), ¬
map(curry(product)'s |λ|(7), enumFromTo(1, 10))}
--> {«script», «script», 5, {7, 14, 21, 28, 35, 42, 49, 56, 63, 70}}
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn

View file

@ -0,0 +1,13 @@
addN: function [n][
return function [x] with 'n [
return x + n
]
]
add2: addN 2
add3: addN 3
do [
print add2 7
print add3 7
]

View file

@ -0,0 +1,5 @@
Plus3 3+
Plus3_1 +3
•Show Plus3 1
•Show Plus3_1 1

View file

@ -0,0 +1,2 @@
4
4

View file

@ -0,0 +1,9 @@
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
}

View file

@ -0,0 +1,31 @@
#include<stdarg.h>
#include<stdio.h>
long int factorial(int n){
if(n>1)
return n*factorial(n-1);
return 1;
}
long int sumOfFactorials(int num,...){
va_list vaList;
long int sum = 0;
va_start(vaList,num);
while(num--)
sum += factorial(va_arg(vaList,int));
va_end(vaList);
return sum;
}
int main()
{
printf("\nSum of factorials of [1,5] : %ld",sumOfFactorials(5,1,2,3,4,5));
printf("\nSum of factorials of [3,5] : %ld",sumOfFactorials(3,3,4,5));
printf("\nSum of factorials of [1,3] : %ld",sumOfFactorials(3,1,2,3));
return 0;
}

View file

@ -0,0 +1,10 @@
shared void run() {
function divide(Integer x, Integer y) => x / y;
value partsOf120 = curry(divide)(120);
print("half of 120 is ``partsOf120(2)``
a third is ``partsOf120(3)``
and a quarter is ``partsOf120(4)``");
}

View file

@ -0,0 +1,4 @@
(def plus-a-hundred (partial + 100))
(assert (=
(plus-a-hundred 1)
101))

View file

@ -0,0 +1,3 @@
(defun curry (function &rest args-1)
(lambda (&rest args-2)
(apply function (append args-1 args-2))))

View file

@ -0,0 +1,3 @@
(funcall (curry #'+ 10) 10)
20

View file

@ -0,0 +1,11 @@
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

View file

@ -0,0 +1,11 @@
void main() {
import std.stdio, std.functional;
int add(int a, int b) {
return a + b;
}
alias add2 = partial!(add, 2);
writeln("Add 2 to 3: ", add(2, 3));
writeln("Add 2 to 3 (curried): ", add2(3));
}

View file

@ -0,0 +1,26 @@
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.

View file

@ -0,0 +1,7 @@
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)

View file

@ -0,0 +1,19 @@
;;
;; curry functional definition
;; (define (curry proc . left-args) (lambda right-args (apply proc (append left-args right-args))))
;;
;; right-curry
;; (define (rcurry proc . right-args) (lambda left-args (apply proc (append left-args right-args))))
;;
(define add42 (curry + 42))
(add42 666) → 708
(map (curry cons 'simon) '( gallubert garfunkel et-merveilles))
→ ((simon . gallubert) (simon . garfunkel) (simon . et-merveilles))
(map (rcurry cons 'simon) '( gallubert garfunkel et-merveilles))
→ ((gallubert . simon) (garfunkel . simon) (et-merveilles . simon))
;Implementation : result of currying :
(curry * 2 3 (+ 2 2))
→ (λ _#:g1004 (#apply-curry #* (2 3 4) _#:g1004))

View file

@ -0,0 +1,14 @@
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)}
);
}
}

View file

@ -0,0 +1,14 @@
#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

View file

@ -0,0 +1,12 @@
#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

View file

@ -0,0 +1,62 @@
-module(currying).
-compile(export_all).
% Function that curry the first or the second argument of a given function of arity 2
curry_first(F,X) ->
fun(Y) -> F(X,Y) end.
curry_second(F,Y) ->
fun(X) -> F(X,Y) end.
% Usual curry
curry(Fun,Arg) ->
case erlang:fun_info(Fun,arity) of
{arity,0} ->
erlang:error(badarg);
{arity,ArityFun} ->
create_ano_fun(ArityFun,Fun,Arg);
_ ->
erlang:error(badarg)
end.
create_ano_fun(Arity,Fun,Arg) ->
Pars =
[{var,1,list_to_atom(lists:flatten(io_lib:format("X~p", [N])))}
|| N <- lists:seq(2,Arity)],
Ano =
{'fun',1,
{clauses,[{clause,1,Pars,[],
[{call,1,{var,1,'Fun'},[{var,1,'Arg'}] ++ Pars}]}]}},
{_,Result,_} = erl_eval:expr(Ano, [{'Arg',Arg},{'Fun',Fun}]),
Result.
% Generalization of the currying
curry_gen(Fun,GivenArgs,PosGivenArgs,PosParArgs) ->
Pos = PosGivenArgs ++ PosParArgs,
case erlang:fun_info(Fun,arity) of
{arity,ArityFun} ->
case ((length(GivenArgs) + length(PosParArgs)) == ArityFun) and
(length(GivenArgs) == length(PosGivenArgs)) and
(length(Pos) == sets:size(sets:from_list(Pos))) of
true ->
fun(ParArgs) ->
case length(ParArgs) == length(PosParArgs) of
true ->
Given = lists:zip(PosGivenArgs,GivenArgs),
Pars = lists:zip(PosParArgs,ParArgs),
{_,Args} = lists:unzip(lists:sort(Given ++ Pars)),
erlang:apply(Fun,Args);
false ->
erlang:error(badarg)
end
end;
false ->
erlang:error(badarg)
end;
_ ->
erlang:error(badarg)
end.

View file

@ -0,0 +1 @@
let addN n = (+) n

View file

@ -0,0 +1,8 @@
> let add2 = addN 2;;
val add2 : (int -> int)
> add2;;
val it : (int -> int) = <fun:addN@1>
> add2 7;;
val it : int = 9

View file

@ -0,0 +1,8 @@
IN: scratchpad 2 [ 3 + ] curry
--- Data stack:
[ 2 3 + ]
IN: scratchpad call
--- Data stack:
5

View file

@ -0,0 +1,9 @@
IN: scratchpad [ 3 4 ] [ 5 + ] compose
--- Data stack:
[ 3 4 5 + ]
IN: scratchpad call
--- Data stack:
3
9

View file

@ -0,0 +1,4 @@
IN: scratchpad { 1 2 3 4 5 } [ 1 + ] { 2 / } append map
--- Data stack:
{ 1 1+1/2 2 2+1/2 3 }

View file

@ -0,0 +1,5 @@
USE: fry
IN: scratchpad 2 3 '[ _ _ + ]
--- Data stack:
[ 2 3 + ]

View file

@ -0,0 +1,4 @@
IN: scratchpad { 1 2 3 4 5 } [ 1 + ] '[ 2 + @ ] map
--- Data stack:
{ 4 5 6 7 8 }

View file

@ -0,0 +1,6 @@
: curry ( x xt1 -- xt2 )
swap 2>r :noname r> postpone literal r> compile, postpone ; ;
5 ' + curry constant +5
5 +5 execute .
7 +5 execute .

View file

@ -0,0 +1,18 @@
' 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

View file

@ -0,0 +1,12 @@
extends Node
func addN(n: int) -> Callable:
return func(x):
return n + x
func _ready():
# Test currying
var add2 := addN(2)
print(add2.call(7))
get_tree().quit() # Exit

View file

@ -0,0 +1,37 @@
package main
import (
"fmt"
"math"
)
func PowN(b float64) func(float64) float64 {
return func(e float64) float64 { return math.Pow(b, e) }
}
func PowE(e float64) func(float64) float64 {
return func(b float64) float64 { return math.Pow(b, e) }
}
type Foo int
func (f Foo) Method(b int) int {
return int(f) + b
}
func main() {
pow2 := PowN(2)
cube := PowE(3)
fmt.Println("2^8 =", pow2(8))
fmt.Println("4³ =", cube(4))
var a Foo = 2
fn1 := a.Method // A "method value", like currying 'a'
fn2 := Foo.Method // A "method expression", like uncurrying
fmt.Println("2 + 2 =", a.Method(2)) // regular method call
fmt.Println("2 + 3 =", fn1(3))
fmt.Println("2 + 4 =", fn2(a, 4))
fmt.Println("3 + 5 =", fn2(Foo(3), 5))
}

View file

@ -0,0 +1,7 @@
def divide = { Number x, Number y ->
x / y
}
def partsOf120 = divide.curry(120)
println "120: half: ${partsOf120(2)}, third: ${partsOf120(3)}, quarter: ${partsOf120(4)}"

View file

@ -0,0 +1,5 @@
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)}"

View file

@ -0,0 +1 @@
\ ->

View file

@ -0,0 +1 @@
\

View file

@ -0,0 +1 @@
->

View file

@ -0,0 +1 @@
\x y -> x + y

View file

@ -0,0 +1 @@
\x -> \y -> x + y

View file

@ -0,0 +1,3 @@
(defn addN [n]
(fn [x]
(+ x n)))

View file

@ -0,0 +1,6 @@
=> (setv add2 (addN 2))
=> (add2 7)
9
=> ((addN 3) 4)
7

View file

@ -0,0 +1,13 @@
procedure main(A)
add2 := addN(2)
write("add2(7) = ",add2(7))
write("add2(1) = ",add2(1))
end
procedure addN(n)
return makeProc{ repeat { (x := (x@&source)[1], x +:= n) } }
end
procedure makeProc(A)
return (@A[1], A[1])
end

View file

@ -0,0 +1,12 @@
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

View file

@ -0,0 +1,7 @@
threePlus=: 3&+
threePlus 7
10
halve =: %&2 NB. % means divide
halve 20
10
someParabola =: _2 3 1 &p. NB. x^2 + 3x - 2

View file

@ -0,0 +1,3 @@
with2=: &2
+with2 3
5

View file

@ -0,0 +1,38 @@
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)));
}
}

View file

@ -0,0 +1,34 @@
import java.util.function.BiFunction;
import java.util.function.Function;
public class Curry {
//Curry a method
public static <T, U, R> Function<T, Function<U, R>> curry(BiFunction<T, U, R> biFunction) {
return t -> u -> biFunction.apply(t, u);
}
public static int add(int x, int y) {
return x + y;
}
public static void curryMethod() {
BiFunction<Integer, Integer, Integer> bif = Curry::add;
Function<Integer, Function<Integer, Integer>> add = curry(bif);
Function<Integer, Integer> add5 = add.apply(5);
System.out.println(add5.apply(2));
}
//Or declare the curried function in one line
public static void curryDirectly() {
Function<Integer, Function<Integer, Integer>> add = x -> y -> x + y;
Function<Integer, Integer> add5 = add.apply(5);
System.out.println(add5.apply(2));
}
//prints 7 and 7
public static void main(String[] args) {
curryMethod();
curryDirectly();
}
}

View file

@ -0,0 +1,10 @@
function addN(n) {
var curry = function(x) {
return x + n;
};
return curry;
}
add2 = addN(2);
alert(add2);
alert(add2(7));

View file

@ -0,0 +1 @@
[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]

View file

@ -0,0 +1,29 @@
(() => {
// (arbitrary arity to fully curried)
// extraCurry :: Function -> Function
let extraCurry = (f, ...args) => {
let intArgs = f.length;
// Recursive currying
let _curry = (xs, ...arguments) =>
xs.length >= intArgs ? (
f.apply(null, xs)
) : function () {
return _curry(xs.concat([].slice.apply(arguments)));
};
return _curry([].slice.call(args, 1));
};
// TEST
// product3:: Num -> Num -> Num -> Num
let product3 = (a, b, c) => a * b * c;
return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.map(extraCurry(product3)(7)(2))
// [14, 28, 42, 56, 70, 84, 98, 112, 126, 140]
})();

View file

@ -0,0 +1 @@
[14, 28, 42, 56, 70, 84, 98, 112, 126, 140]

View file

@ -0,0 +1,34 @@
(function () {
// curry :: ((a, b) -> c) -> a -> b -> c
function curry(f) {
return function (a) {
return function (b) {
return f(a, b);
};
};
}
// TESTS
// product :: Num -> Num -> Num
function product(a, b) {
return a * b;
}
// return typeof curry(product);
// --> function
// return typeof curry(product)(7)
// --> function
//return typeof curry(product)(7)(9)
// --> number
return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.map(curry(product)(7))
// [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
})();

View file

@ -0,0 +1 @@
[7, 14, 21, 28, 35, 42, 49, 56, 63, 70]

View file

@ -0,0 +1,34 @@
(function () {
// (arbitrary arity to fully curried)
// extraCurry :: Function -> Function
function extraCurry(f) {
// Recursive currying
function _curry(xs) {
return xs.length >= intArgs ? (
f.apply(null, xs)
) : function () {
return _curry(xs.concat([].slice.apply(arguments)));
};
}
var intArgs = f.length;
return _curry([].slice.call(arguments, 1));
}
// TEST
// product3:: Num -> Num -> Num -> Num
function product3(a, b, c) {
return a * b * c;
}
return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.map(extraCurry(product3)(7)(2))
// [14, 28, 42, 56, 70, 84, 98, 112, 126, 140]
})();

View file

@ -0,0 +1 @@
[14, 28, 42, 56, 70, 84, 98, 112, 126, 140]

View file

@ -0,0 +1 @@
(a,b) => expr_using_a_and_b

View file

@ -0,0 +1 @@
a => b => expr_using_a_and_b

View file

@ -0,0 +1,23 @@
let
fix = // This is a variant of the Applicative order Y combinator
f => (f => f(f))(g => f((...a) => g(g)(...a))),
curry =
f => (
fix(
z => (n,...a) => (
n>0
?b => z(n-1,...a,b)
:f(...a)))
(f.length)),
curryrest =
f => (
fix(
z => (n,...a) => (
n>0
?b => z(n-1,...a,b)
:(...b) => f(...a,...b)))
(f.length)),
curriedmax=curry(Math.max),
curryrestedmax=curryrest(Math.max);
print(curriedmax(8)(4),curryrestedmax(8)(4)(),curryrestedmax(8)(4)(9,7,2));
// 8,8,9

View file

@ -0,0 +1,27 @@
(() => {
// curry :: ((a, b) -> c) -> a -> b -> c
let curry = f => a => b => f(a, b);
// TEST
// product :: Num -> Num -> Num
let product = (a, b) => a * b,
// Int -> Int -> Maybe Int -> [Int]
range = (m, n, step) => {
let d = (step || 1) * (n >= m ? 1 : -1);
return Array.from({
length: Math.floor((n - m) / d) + 1
}, (_, i) => m + (i * d));
}
return range(1, 10)
.map(curry(product)(7))
// [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
})();

View file

@ -0,0 +1,3 @@
def plus(x): . + x;
def plus5: plus(5);

View file

@ -0,0 +1 @@
3 | plus5

View file

@ -0,0 +1,4 @@
function addN(n::Number)::Function
adder(x::Number) = n + x
return adder
end

View file

@ -0,0 +1,10 @@
// version 1.1.2
fun curriedAdd(x: Int) = { y: Int -> x + y }
fun main(args: Array<String>) {
val a = 2
val b = 3
val sum = curriedAdd(a)(b)
println("$a + $b = $sum")
}

View file

@ -0,0 +1,4 @@
(defun curry (f arg)
(lambda (x)
(apply f
(list arg x))))

View file

@ -0,0 +1 @@
(funcall (curry #'+/2 10) 10)

View file

@ -0,0 +1,13 @@
1) just define function a binary function:
{def power {lambda {:a :b} {pow :a :b}}}
-> power
2) and use it:
{power 2 8} // power is a function waiting for two numbers
-> 256
{{power 2} 8} // {power 2} is a function waiting for the missing number
-> 256
{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

View file

@ -0,0 +1,9 @@
addN := {
takes '[n].
{
$1 + n.
}.
}.
add3 := addN 3.
add3 (4). ;; 7

View file

@ -0,0 +1,3 @@
;; addN (3) (4). ;; Syntax error!
;; (addN (3)) (4). ;; Syntax error!
addN (3) call (4). ;; Works as expected.

View file

@ -0,0 +1,10 @@
addN := {
takes '[n].
Object clone tap {
self do := {
$1 + n.
}.
}.
}.
addN 3 do 4. ;; 7

View file

@ -0,0 +1,3 @@
| ?- logtalk << call([Z]>>(call([X,Y]>>(Y is X*X), 5, R), Z is R*R), T).
T = 625
yes

View file

@ -0,0 +1,17 @@
function curry2(f)
return function(x)
return function(y)
return f(x,y)
end
end
end
function add(x,y)
return x+y
end
local adder = curry2(add)
assert(adder(3)(4) == 3+4)
local add2 = adder(2)
assert(add2(3) == 2+3)
assert(add2(5) == 2+5)

View file

@ -0,0 +1,35 @@
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({},{
__call = function(me, n, m, ...)return me[n*256+m](...)end,
__index = function(me,k)
local n,m = floor(k / 256), k % 256
local r,s = {},{} for i=1,m do r[i],s[i]='_'..i,'_'..i end s[1+#s]='...'
r,s=cat(r,','),cat(s,',')
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,env) )
return rawget(me,k)
end})
env = {CALL=call,ME=curryHelper,select=select}
function curry(...)
local pn,n,fn = select('#',...),...
if pn==1 then n,fn = debug.getinfo(n, 'u'),n ; n = n and n.nparams end
if type(n)~='number' or n~=floor(n)then return nil,'invalid curry'
elseif n<=0 then return fn -- edge case
else return curryHelper(n,1,fn)
end
end
end
-- test
function add(x,y)
return x+y
end
local adder = curry(add) -- get params count from debug.getinfo
assert(adder(3)(4) == 3+4)
local add2 = adder(2)
assert(add2(3) == 2+3)
assert(add2(5) == 2+5)

View file

@ -0,0 +1,42 @@
Module LikeGroovy {
divide=lambda (x, y)->x/y
partsof120=lambda divide ->divide(120, ![])
Print "half of 120 is ";partsof120(2)
Print "a third is ";partsof120(3)
Print "and a quarter is ";partsof120(4)
}
LikeGroovy
Module Joke {
\\ we can call F1(), with any number of arguments, and always read one and then
\\ call itself passing the remain arguments
\\ ![] take stack of values and place it in the next call.
F1=lambda -> {
if empty then exit
Read x
=x+lambda(![])
}
Print F1(F1(2),2,F1(-4))=0
Print F1(-4,F1(2),2)=0
Print F1(2, F1(F1(2),2))=F1(F1(F1(2),2),2)
Print F1(F1(F1(2),2),2)=6
Print F1(2, F1(2, F1(2),2))=F1(F1(F1(2),2, F1(2)),2)
Print F1(F1(F1(2),2, F1(2)),2)=8
Print F1(2, F1(10, F1(2, F1(2),2)))=F1(F1(F1(2),2, F1(2)),2, 10)
Print F1(F1(F1(2),2, F1(2)),2, 10)=18
Print F1(2,2,2,2,10)=18
Print F1()=0
Group F2 {
Sum=0
Function Add (x){
.Sum+=x
=x
}
}
Link F2.Add() to F2()
Print F1(F1(F1(F2(2)),F2(2), F1(F2(2))),F2(2))=8
Print F2.Sum=8
}
Joke

View file

@ -0,0 +1,26 @@
Module Puzzle {
Global Group F2 {
Sum=0
Sum2=0
Function Add (x){
.Sum+=x
=x
}
}
F1=lambda -> {
if empty then exit
Read x
Print ">>>", F2.Sum
F2.Sum2++ ' add one each time we read x
=x+lambda(![])
}
Link F2.Add() to F2()
P=F1(F1(F1(F2(2)),F2(2), F1(F2(2))),F2(2))=8
Print F2.Sum=8
Print F2.Sum2=7
\\ We read 7 times x, but we get 8, 2+2+2+2
\\ So 3 times x was zero, or not?
\\ but where we pass zero?
\\ zero return from F1 if no argument pass, so how x get zero??
}
Puzzle

View file

@ -0,0 +1,20 @@
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))")
}
}

View file

@ -0,0 +1,4 @@
proc addN[T](n: T): auto = (proc(x: T): T = x + n)
let add2 = addN(2)
echo add2(7)

View file

@ -0,0 +1,6 @@
import sugar
proc addM[T](n: T): auto = (x: T) => x + n
let add3 = addM(3)
echo add3(7)

View file

@ -0,0 +1,4 @@
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 *)

View file

@ -0,0 +1,2 @@
let curry f x y = f (x,y)
(* Type signature: ('a * 'b -> 'c) -> 'a -> 'b -> 'c *)

View file

@ -0,0 +1,3 @@
2 #+ curry => 2+
5 2+ .
7 ok

View file

@ -0,0 +1,7 @@
(define (addN n)
(lambda (x) (+ x n)))
(let ((add10 (addN 10))
(add20 (addN 20)))
(print "(add10 4) ==> " (add10 4))
(print "(add20 4) ==> " (add20 4)))

View file

@ -0,0 +1,2 @@
curriedPlus(x)=y->x+y;
curriedPlus(1)(2)

View file

@ -0,0 +1,95 @@
<?php
function curry($callable)
{
if (_number_of_required_params($callable) === 0) {
return _make_function($callable);
}
if (_number_of_required_params($callable) === 1) {
return _curry_array_args($callable, _rest(func_get_args()));
}
return _curry_array_args($callable, _rest(func_get_args()));
}
function _curry_array_args($callable, $args, $left = true)
{
return function () use ($callable, $args, $left) {
if (_is_fullfilled($callable, $args)) {
return _execute($callable, $args, $left);
}
$newArgs = array_merge($args, func_get_args());
if (_is_fullfilled($callable, $newArgs)) {
return _execute($callable, $newArgs, $left);
}
return _curry_array_args($callable, $newArgs, $left);
};
}
function _number_of_required_params($callable)
{
if (is_array($callable)) {
$refl = new \ReflectionClass($callable[0]);
$method = $refl->getMethod($callable[1]);
return $method->getNumberOfRequiredParameters();
}
$refl = new \ReflectionFunction($callable);
return $refl->getNumberOfRequiredParameters();
}
function _make_function($callable)
{
if (is_array($callable))
return function() use($callable) {
return call_user_func_array($callable, func_get_args());
};
return $callable;
}
function _execute($callable, $args, $left)
{
if (! $left) {
$args = array_reverse($args);
}
$placeholders = _placeholder_positions($args);
if (0 < count($placeholders)) {
$n = _number_of_required_params($callable);
if ($n <= _last($placeholders[count($placeholders) - 1])) {
throw new \Exception('Argument Placeholder found on unexpected position!');
}
foreach ($placeholders as $i) {
$args[$i] = $args[$n];
array_splice($args, $n, 1);
}
}
return call_user_func_array($callable, $args);
}
function _placeholder_positions($args)
{
return array_keys(array_filter($args, '_is_placeholder'));
}
function _is_fullfilled($callable, $args)
{
$args = array_filter($args, function($arg) {
return ! _is_placeholder($arg);
});
return count($args) >= _number_of_required_params($callable);
}
function _is_placeholder($arg)
{
return $arg instanceof Placeholder;
}
function _rest(array $args)
{
return array_slice($args, 1);
}
function product($a, $b)
{
return $a * $b;
}
echo json_encode(array_map(curry('product', 7), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));

View file

@ -0,0 +1,15 @@
sub curry{
my ($func, @args) = @_;
sub {
#This @_ is later
&$func(@args, @_);
}
}
sub plusXY{
$_[0] + $_[1];
}
my $plusXOne = curry(\&plusXY, 1);
print &$plusXOne(3), "\n";

View file

@ -0,0 +1,20 @@
(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">curries</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<!--

View file

@ -0,0 +1 @@
function Add($x) { return { param($y) return $y + $x }.GetNewClosure() }

View file

@ -0,0 +1 @@
& (Add 1) 2

View file

@ -0,0 +1 @@
(4,9,16,25 | ForEach-Object { & (add $_) ([Math]::Sqrt($_)) }) -join ", "

View file

@ -0,0 +1,4 @@
def addN(n):
def adder(x):
return x + n
return adder

View file

@ -0,0 +1,5 @@
>>> add2 = addN(2)
>>> add2
<function adder at 0x009F1E30>
>>> add2(7)
9

View file

@ -0,0 +1,10 @@
>>> from functools import partial
>>> from operator import add
>>> add2 = partial(add, 2)
>>> add2
functools.partial(<built-in function add>, 2)
>>> add2(7)
9
>>> double = partial(map, lambda x: x*2)
>>> print(*double(range(5)))
0 2 4 6 8

View file

@ -0,0 +1,13 @@
>>> from toolz import curry
>>> import operator
>>> add = curry(operator.add)
>>> add2 = add(2)
>>> add2
<built-in function add>
>>> add2(7)
9
>>> # Toolz also has pre-curried versions of most HOFs from builtins, stdlib, and toolz
>>>from toolz.curried import map
>>> double = map(lambda x: x*2)
>>> print(*double(range(5)))
0 2 4 6 8

View file

@ -0,0 +1,54 @@
# AUTOMATIC CURRYING AND UNCURRYING OF EXISTING FUNCTIONS
# curry :: ((a, b) -> c) -> a -> b -> c
def curry(f):
return lambda a: lambda b: f(a, b)
# uncurry :: (a -> b -> c) -> ((a, b) -> c)
def uncurry(f):
return lambda x, y: f(x)(y)
# EXAMPLES --------------------------------------
# A plain uncurried function with 2 arguments,
# justifyLeft :: Int -> String -> String
def justifyLeft(n, s):
return (s + (n * ' '))[:n]
# and a similar, but manually curried, function.
# justifyRight :: Int -> String -> String
def justifyRight(n):
return lambda s: (
((n * ' ') + s)[-n:]
)
# CURRYING and UNCURRYING at run-time:
def main():
for s in [
'Manually curried using a lambda:',
'\n'.join(map(
justifyRight(5),
['1', '9', '10', '99', '100', '1000']
)),
'\nAutomatically uncurried:',
uncurry(justifyRight)(5, '10000'),
'\nAutomatically curried',
'\n'.join(map(
curry(justifyLeft)(10),
['1', '9', '10', '99', '100', '1000']
))
]:
print (s)
main()

View file

@ -0,0 +1,2 @@
[ ' [ ' ] swap nested join
]'[ nested join ] is curried ( x --> [ )

Some files were not shown because too many files have changed in this diff Show more