Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
3
Task/Higher-order-functions/00-META.yaml
Normal file
3
Task/Higher-order-functions/00-META.yaml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Higher-order_functions
|
||||
note: Programming language concepts
|
||||
8
Task/Higher-order-functions/00-TASK.txt
Normal file
8
Task/Higher-order-functions/00-TASK.txt
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
;Task:
|
||||
Pass a function ''as an argument'' to another function.
|
||||
|
||||
|
||||
;Related task:
|
||||
* [[First-class functions]]
|
||||
<br><br>
|
||||
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
F first(function)
|
||||
R function()
|
||||
|
||||
F second()
|
||||
R ‘second’
|
||||
|
||||
V result = first(second)
|
||||
print(result)
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
macro PrintOutput,input,addr
|
||||
; input: desired function's input
|
||||
; addr: function you wish to call
|
||||
LDA #<\addr ;#< represents this number's low byte
|
||||
STA z_L
|
||||
LDA #>\addr ;#> represents this number's high byte
|
||||
STA z_H
|
||||
LDA \input
|
||||
JSR doPrintOutput
|
||||
endm
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
PrintOutput:
|
||||
; prints the output of the function "foo" to the screen.
|
||||
; input:
|
||||
; A = input for the function "foo".
|
||||
; z_L = contains the low byte of the memory address of "foo"
|
||||
; z_H = contains the high byte of the memory address of "foo"
|
||||
|
||||
pha
|
||||
|
||||
LDA z_L
|
||||
STA smc+1 ;store in the low byte of the operand
|
||||
LDA z_H
|
||||
STA smc+2 ;store in the high byte of the operand
|
||||
|
||||
pla
|
||||
|
||||
smc:
|
||||
JSR $1234
|
||||
;uses self-modifying code to overwrite the destination with the address of the passed function.
|
||||
;assuming that function ends in an RTS, execution will return to this line after the function is done.
|
||||
JSR PrintAccumulator
|
||||
|
||||
rts
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
LEA foo,A0
|
||||
JSR bar
|
||||
|
||||
JMP * ;HALT
|
||||
|
||||
bar:
|
||||
MOVE.L A0,-(SP)
|
||||
RTS ;JMP foo
|
||||
|
||||
foo:
|
||||
RTS ;do nothing and return. This rts retuns execution just after "JSR bar" but before "JMP *".
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
: pass-me
|
||||
"I was passed\n" . ;
|
||||
: passer
|
||||
w:exec ;
|
||||
\ pass 'pass-me' to 'passer'
|
||||
' pass-me passer
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
PROC first = (PROC(LONG REAL)LONG REAL f) LONG REAL:
|
||||
(
|
||||
f(1) + 2
|
||||
);
|
||||
|
||||
PROC second = (LONG REAL x)LONG REAL:
|
||||
(
|
||||
x/2
|
||||
);
|
||||
|
||||
main: (
|
||||
printf(($xg(5,2)l$,first(second)))
|
||||
)
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
twice:{x[x[y]]}
|
||||
echo twice "Hello!"
|
||||
13
Task/Higher-order-functions/ATS/higher-order-functions.ats
Normal file
13
Task/Higher-order-functions/ATS/higher-order-functions.ats
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
#include
|
||||
"share/atspre_staload.hats"
|
||||
|
||||
fun app_to_0 (f: (int) -> int): int = f (0)
|
||||
|
||||
implement
|
||||
main0 () =
|
||||
{
|
||||
//
|
||||
val () = assertloc (app_to_0(lam(x) => x+1) = 1)
|
||||
val () = assertloc (app_to_0(lam(x) => 10*(x+1)) = 10)
|
||||
//
|
||||
} (* end of [main0] *)
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package {
|
||||
public class MyClass {
|
||||
|
||||
public function first(func:Function):String {
|
||||
return func.call();
|
||||
}
|
||||
|
||||
public function second():String {
|
||||
return "second";
|
||||
}
|
||||
|
||||
public static function main():void {
|
||||
var result:String = first(second);
|
||||
trace(result);
|
||||
result = first(function() { return "third"; });
|
||||
trace(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
17
Task/Higher-order-functions/Ada/higher-order-functions-1.ada
Normal file
17
Task/Higher-order-functions/Ada/higher-order-functions-1.ada
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
with Ada.Text_Io; use Ada.Text_Io;
|
||||
|
||||
procedure Subprogram_As_Argument is
|
||||
type Proc_Access is access procedure;
|
||||
|
||||
procedure Second is
|
||||
begin
|
||||
Put_Line("Second Procedure");
|
||||
end Second;
|
||||
|
||||
procedure First(Proc : Proc_Access) is
|
||||
begin
|
||||
Proc.all;
|
||||
end First;
|
||||
begin
|
||||
First(Second'Access);
|
||||
end Subprogram_As_Argument;
|
||||
52
Task/Higher-order-functions/Ada/higher-order-functions-2.ada
Normal file
52
Task/Higher-order-functions/Ada/higher-order-functions-2.ada
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
with Ada.Text_Io; use Ada.Text_Io;
|
||||
|
||||
procedure Subprogram_As_Argument_2 is
|
||||
|
||||
-- Definition of an access to long_float
|
||||
|
||||
type Lf_Access is access Long_Float;
|
||||
|
||||
-- Definition of a function returning Lf_Access taking an
|
||||
-- integer as a parameter
|
||||
|
||||
function Func_To_Be_Passed(Item : Integer) return Lf_Access is
|
||||
Result : Lf_Access := new Long_Float;
|
||||
begin
|
||||
Result.All := 3.14159 * Long_Float(Item);
|
||||
return Result;
|
||||
end Func_To_Be_Passed;
|
||||
|
||||
-- Definition of an access to function type matching the function
|
||||
-- signature above
|
||||
|
||||
type Func_Access is access function(Item : Integer) return Lf_Access;
|
||||
|
||||
-- Definition of an integer access type
|
||||
|
||||
type Int_Access is access Integer;
|
||||
|
||||
-- Define a function taking an instance of Func_Access as its
|
||||
-- parameter and returning an integer access type
|
||||
|
||||
function Complex_Func(Item : Func_Access; Parm2 : Integer) return Int_Access is
|
||||
Result : Int_Access := new Integer;
|
||||
begin
|
||||
Result.All := Integer(Item(Parm2).all / 3.14149);
|
||||
return Result;
|
||||
end Complex_Func;
|
||||
|
||||
-- Declare an access variable to hold the access to the function
|
||||
|
||||
F_Ptr : Func_Access := Func_To_Be_Passed'access;
|
||||
|
||||
-- Declare an access to integer variable to hold the result
|
||||
|
||||
Int_Ptr : Int_Access;
|
||||
|
||||
begin
|
||||
|
||||
-- Call the function using the access variable
|
||||
|
||||
Int_Ptr := Complex_Func(F_Ptr, 3);
|
||||
Put_Line(Integer'Image(Int_Ptr.All));
|
||||
end Subprogram_As_Argument_2;
|
||||
25
Task/Higher-order-functions/Aime/higher-order-functions.aime
Normal file
25
Task/Higher-order-functions/Aime/higher-order-functions.aime
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
integer
|
||||
average(integer p, integer q)
|
||||
{
|
||||
return (p + q) / 2;
|
||||
}
|
||||
|
||||
|
||||
void
|
||||
out(integer p, integer q, integer (*f) (integer, integer))
|
||||
{
|
||||
o_integer(f(p, q));
|
||||
o_byte('\n');
|
||||
}
|
||||
|
||||
|
||||
integer
|
||||
main(void)
|
||||
{
|
||||
# display the minimum, the maximum and the average of 117 and 319
|
||||
out(117, 319, min);
|
||||
out(117, 319, max);
|
||||
out(117, 319, average);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
PROC compute(func, val)
|
||||
DEF s[10] : STRING
|
||||
WriteF('\s\n', RealF(s,func(val),4))
|
||||
ENDPROC
|
||||
|
||||
PROC sin_wrap(val) IS Fsin(val)
|
||||
PROC cos_wrap(val) IS Fcos(val)
|
||||
|
||||
PROC main()
|
||||
compute({sin_wrap}, 0.0)
|
||||
compute({cos_wrap}, 3.1415)
|
||||
ENDPROC
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
-- This handler takes a script object (singer)
|
||||
-- with another handler (call).
|
||||
on sing about topic by singer
|
||||
call of singer for "Of " & topic & " I sing"
|
||||
end sing
|
||||
|
||||
-- Define a handler in a script object,
|
||||
-- then pass the script object.
|
||||
script cellos
|
||||
on call for what
|
||||
say what using "Cellos"
|
||||
end call
|
||||
end script
|
||||
sing about "functional programming" by cellos
|
||||
|
||||
-- Pass a different handler. This one is a closure
|
||||
-- that uses a variable (voice) from its context.
|
||||
on hire for voice
|
||||
script
|
||||
on call for what
|
||||
say what using voice
|
||||
end call
|
||||
end script
|
||||
end hire
|
||||
sing about "closures" by (hire for "Pipe Organ")
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
on run
|
||||
-- PASSING FUNCTIONS AS ARGUMENTS TO
|
||||
-- MAP, FOLD/REDUCE, AND FILTER, ACROSS A LIST
|
||||
|
||||
set lstRange to {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
|
||||
|
||||
map(squared, lstRange)
|
||||
--> {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100}
|
||||
|
||||
foldl(summed, 0, map(squared, lstRange))
|
||||
--> 385
|
||||
|
||||
filter(isEven, lstRange)
|
||||
--> {0, 2, 4, 6, 8, 10}
|
||||
|
||||
|
||||
-- OR MAPPING OVER A LIST OF FUNCTIONS
|
||||
|
||||
map(testFunction, {doubled, squared, isEven})
|
||||
|
||||
--> {{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20},
|
||||
-- {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100},
|
||||
-- {true, false, true, false, true, false, true, false, true, false, true}}
|
||||
end run
|
||||
|
||||
-- testFunction :: (a -> b) -> [b]
|
||||
on testFunction(f)
|
||||
map(f, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
|
||||
end testFunction
|
||||
|
||||
|
||||
-- MAP, REDUCE, FILTER
|
||||
|
||||
-- Returns a new list consisting of the results of applying the
|
||||
-- provided function to each element of the first list
|
||||
-- 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
|
||||
|
||||
-- Applies a function against an accumulator and
|
||||
-- each list element (from left-to-right) to reduce it
|
||||
-- to a single return value
|
||||
|
||||
-- In some languages, like JavaScript, this is called reduce()
|
||||
|
||||
-- Arguments: function, initial value of accumulator, list
|
||||
-- foldl :: (a -> b -> a) -> a -> [b] -> a
|
||||
on foldl(f, startValue, xs)
|
||||
tell mReturn(f)
|
||||
set v to startValue
|
||||
set lng to length of xs
|
||||
repeat with i from 1 to lng
|
||||
set v to |λ|(v, item i of xs, i, xs)
|
||||
end repeat
|
||||
return v
|
||||
end tell
|
||||
end foldl
|
||||
|
||||
|
||||
-- Sublist of those elements for which the predicate
|
||||
-- function returns true
|
||||
-- filter :: (a -> Bool) -> [a] -> [a]
|
||||
on filter(f, xs)
|
||||
tell mReturn(f)
|
||||
set lst to {}
|
||||
set lng to length of xs
|
||||
repeat with i from 1 to lng
|
||||
set v to item i of xs
|
||||
if |λ|(v, i, xs) then set end of lst to v
|
||||
end repeat
|
||||
return lst
|
||||
end tell
|
||||
end filter
|
||||
|
||||
-- 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
|
||||
|
||||
-- HANDLER FUNCTIONS TO BE PASSED AS ARGUMENTS
|
||||
|
||||
-- squared :: Number -> Number
|
||||
on squared(x)
|
||||
x * x
|
||||
end squared
|
||||
|
||||
-- doubled :: Number -> Number
|
||||
on doubled(x)
|
||||
x * 2
|
||||
end doubled
|
||||
|
||||
-- summed :: Number -> Number -> Number
|
||||
on summed(a, b)
|
||||
a + b
|
||||
end summed
|
||||
|
||||
-- isEven :: Int -> Bool
|
||||
on isEven(x)
|
||||
x mod 2 = 0
|
||||
end isEven
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
{{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20},
|
||||
{0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100},
|
||||
{true, false, true, false, true, false, true, false, true, false, true}}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
script aScript
|
||||
on aHandler(aParameter)
|
||||
say aParameter
|
||||
end aHandler
|
||||
end script
|
||||
|
||||
on receivingHandler(passedScript)
|
||||
passedScript's aHandler("Hello")
|
||||
end receivingHandler
|
||||
|
||||
receivingHandler(aScript)
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
on aHandler(aParameter)
|
||||
say aParameter
|
||||
end aHandler
|
||||
|
||||
on receivingHandler(passedHandler)
|
||||
script o
|
||||
property h : passedHandler
|
||||
end script
|
||||
|
||||
o's h("Hello")
|
||||
end receivingHandler
|
||||
|
||||
receivingHandler(aHandler)
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
doSthWith: function [x y f][
|
||||
f x y
|
||||
]
|
||||
|
||||
print [ "add:" doSthWith 2 3 $[x y][x+y] ]
|
||||
print [ "multiply:" doSthWith 2 3 $[x y][x*y] ]
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
f(x) {
|
||||
return "This " . x
|
||||
}
|
||||
|
||||
g(x) {
|
||||
return "That " . x
|
||||
}
|
||||
|
||||
show(fun) {
|
||||
msgbox % %fun%("works")
|
||||
}
|
||||
|
||||
show(Func("f")) ; either create a Func object
|
||||
show("g") ; or just name the function
|
||||
return
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
REM Test passing a function to a function:
|
||||
PRINT FNtwo(FNone(), 10, 11)
|
||||
END
|
||||
|
||||
REM Function to be passed:
|
||||
DEF FNone(x, y) = (x + y) ^ 2
|
||||
|
||||
REM Function taking a function as an argument:
|
||||
DEF FNtwo(RETURN f%, x, y) = FN(^f%)(x, y)
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
Uniq ← ⍷
|
||||
|
||||
•Show uniq {𝕎𝕩} 5‿6‿7‿5
|
||||
|
|
@ -0,0 +1 @@
|
|||
⟨ 5 6 7 ⟩
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
( (plus=a b.!arg:(?a.?b)&!a+!b)
|
||||
& ( print
|
||||
= text a b func
|
||||
. !arg:(?a.?b.(=?func).?text)
|
||||
& out$(str$(!text "(" !a "," !b ")=" func$(!a.!b)))
|
||||
)
|
||||
& print$(3.7.'$plus.add)
|
||||
& print
|
||||
$ ( 3
|
||||
. 7
|
||||
. (=a b.!arg:(?a.?b)&!a*!b)
|
||||
. multiply
|
||||
)
|
||||
);
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
add = { a, b | a + b }
|
||||
|
||||
doit = { f, a, b | f a, b }
|
||||
|
||||
p doit ->add 1 2 #prints 3
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
blsq ) {1 2 3 4}{5.+}m[
|
||||
{6 7 8 9}
|
||||
21
Task/Higher-order-functions/C++/higher-order-functions-1.cpp
Normal file
21
Task/Higher-order-functions/C++/higher-order-functions-1.cpp
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
// Use <functional> for C++11
|
||||
#include <tr1/functional>
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
using namespace std::tr1;
|
||||
|
||||
void first(function<void()> f)
|
||||
{
|
||||
f();
|
||||
}
|
||||
|
||||
void second()
|
||||
{
|
||||
cout << "second\n";
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
first(second);
|
||||
}
|
||||
23
Task/Higher-order-functions/C++/higher-order-functions-2.cpp
Normal file
23
Task/Higher-order-functions/C++/higher-order-functions-2.cpp
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
#include <iostream>
|
||||
#include <functional>
|
||||
|
||||
template<class Func>
|
||||
typename Func::result_type first(Func func, typename Func::argument_type arg)
|
||||
{
|
||||
return func(arg);
|
||||
}
|
||||
|
||||
class second : public std::unary_function<int, int>
|
||||
{
|
||||
public:
|
||||
result_type operator()(argument_type arg) const
|
||||
{
|
||||
return arg * arg;
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << first(second(), 2) << std::endl;
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
using System;
|
||||
|
||||
// A delegate declaration. Because delegates are types, they can exist directly in namespaces.
|
||||
delegate int Func2(int a, int b);
|
||||
|
||||
class Program
|
||||
{
|
||||
static int Add(int a, int b)
|
||||
{
|
||||
return a + b;
|
||||
}
|
||||
|
||||
static int Mul(int a, int b)
|
||||
{
|
||||
return a * b;
|
||||
}
|
||||
|
||||
static int Div(int a, int b)
|
||||
{
|
||||
return a / b;
|
||||
}
|
||||
|
||||
static int Call(Func2 f, int a, int b)
|
||||
{
|
||||
// Invoking a delegate like a method is syntax sugar; this compiles down to f.Invoke(a, b);
|
||||
return f(a, b);
|
||||
}
|
||||
|
||||
static void Main()
|
||||
{
|
||||
int a = 6;
|
||||
int b = 2;
|
||||
|
||||
// Delegates must be created using the "constructor" syntax in C# 1.0; in C# 2.0 and above, only the name of the method is required (when a target type exists, such as in an assignment to a variable with a delegate type or usage in a function call with a parameter of a delegate type; initializers of implicitly typed variables must use the constructor syntax as a raw method has no delegate type). Overload resolution is performed using the parameter types of the target delegate type.
|
||||
Func2 add = new Func2(Add);
|
||||
Func2 mul = new Func2(Mul);
|
||||
Func2 div = new Func2(Div);
|
||||
|
||||
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call(add, a, b));
|
||||
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call(mul, a, b));
|
||||
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(div, a, b));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
using System;
|
||||
|
||||
delegate int Func2(int a, int b);
|
||||
|
||||
class Program
|
||||
{
|
||||
static int Call(Func2 f, int a, int b)
|
||||
{
|
||||
return f(a, b);
|
||||
}
|
||||
|
||||
static void Main()
|
||||
{
|
||||
int a = 6;
|
||||
int b = 2;
|
||||
|
||||
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x + y; }, a, b));
|
||||
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x * y; }, a, b));
|
||||
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call(delegate(int x, int y) { return x / y; }, a, b));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
using System;
|
||||
|
||||
class Program
|
||||
{
|
||||
static int Call(Func<int, int, int> f, int a, int b)
|
||||
{
|
||||
return f(a, b);
|
||||
}
|
||||
|
||||
static void Main()
|
||||
{
|
||||
int a = 6;
|
||||
int b = 2;
|
||||
|
||||
// No lengthy delegate keyword.
|
||||
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call((int x, int y) => { return x + y; }, a, b));
|
||||
|
||||
// Parameter types can be inferred.
|
||||
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call((x, y) => { return x * y; }, a, b));
|
||||
|
||||
// Expression lambdas are even shorter (and are most idiomatic).
|
||||
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call((x, y) => x / y, a, b));
|
||||
}
|
||||
}
|
||||
9
Task/Higher-order-functions/C/higher-order-functions-1.c
Normal file
9
Task/Higher-order-functions/C/higher-order-functions-1.c
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
void myFuncSimple( void (*funcParameter)(void) )
|
||||
{
|
||||
/* ... */
|
||||
|
||||
(*funcParameter)(); /* Call the passed function. */
|
||||
funcParameter(); /* Same as above with slight different syntax. */
|
||||
|
||||
/* ... */
|
||||
}
|
||||
5
Task/Higher-order-functions/C/higher-order-functions-2.c
Normal file
5
Task/Higher-order-functions/C/higher-order-functions-2.c
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
void funcToBePassed(void);
|
||||
|
||||
/* ... */
|
||||
|
||||
myFuncSimple(&funcToBePassed);
|
||||
13
Task/Higher-order-functions/C/higher-order-functions-3.c
Normal file
13
Task/Higher-order-functions/C/higher-order-functions-3.c
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
int* myFuncComplex( double* (*funcParameter)(long* parameter) )
|
||||
{
|
||||
long inLong;
|
||||
double* outDouble;
|
||||
long *inLong2 = &inLong;
|
||||
|
||||
/* ... */
|
||||
|
||||
outDouble = (*funcParameter)(&inLong); /* Call the passed function and store returned pointer. */
|
||||
outDouble = funcParameter(inLong2); /* Same as above with slight different syntax. */
|
||||
|
||||
/* ... */
|
||||
}
|
||||
7
Task/Higher-order-functions/C/higher-order-functions-4.c
Normal file
7
Task/Higher-order-functions/C/higher-order-functions-4.c
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
double* funcToBePassed(long* parameter);
|
||||
|
||||
/* ... */
|
||||
|
||||
int* outInt;
|
||||
|
||||
outInt = myFuncComplex(&funcToBePassed);
|
||||
5
Task/Higher-order-functions/C/higher-order-functions-5.c
Normal file
5
Task/Higher-order-functions/C/higher-order-functions-5.c
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
int* (*funcPointer)( double* (*funcParameter)(long* parameter) );
|
||||
|
||||
/* ... */
|
||||
|
||||
funcPointer = &myFuncComplex;
|
||||
24
Task/Higher-order-functions/CLU/higher-order-functions.clu
Normal file
24
Task/Higher-order-functions/CLU/higher-order-functions.clu
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
% Functions can be passed to other functions using the 'proctype'
|
||||
% type generator. The same works for iterators, using 'itertype'
|
||||
|
||||
% Here are two functions
|
||||
square = proc (n: int) returns (int) return (n*n) end square
|
||||
cube = proc (n: int) returns (int) return (n*n*n) end cube
|
||||
|
||||
% Here is a function that takes another function
|
||||
do_calcs = proc (from, to: int, title: string,
|
||||
fn: proctype (int) returns (int))
|
||||
po: stream := stream$primary_output()
|
||||
|
||||
stream$putleft(po, title, 8)
|
||||
stream$puts(po, " -> ")
|
||||
for i: int in int$from_to(from,to) do
|
||||
stream$putright(po, int$unparse(fn(i)), 5)
|
||||
end
|
||||
stream$putc(po, '\n')
|
||||
end do_calcs
|
||||
|
||||
start_up = proc ()
|
||||
do_calcs(1, 10, "Squares", square)
|
||||
do_calcs(1, 10, "Cubes", cube)
|
||||
end start_up
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
map f [x:xs] = [f x:map f xs]
|
||||
map f [] = []
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
incr x = x + 1
|
||||
|
||||
Start = map incr [1..10]
|
||||
|
|
@ -0,0 +1 @@
|
|||
Start = map (\x -> x + 1) [1..10]
|
||||
|
|
@ -0,0 +1 @@
|
|||
Start = map ((+) 1) [1..10]
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
(defn append-hello [s]
|
||||
(str "Hello " s))
|
||||
|
||||
(defn modify-string [f s]
|
||||
(f s))
|
||||
|
||||
(println (modify-string append-hello "World!"))
|
||||
|
|
@ -0,0 +1 @@
|
|||
double = [1,2,3].map (x) -> x*2
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
fn = -> return 8
|
||||
sum = (a, b) -> a() + b()
|
||||
sum(fn, fn) # => 16
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
bowl = ["Cheese", "Tomato"]
|
||||
|
||||
smash = (ingredient) ->
|
||||
return "Smashed #{ingredient}"
|
||||
|
||||
contents = smash ingredient for ingredient in bowl
|
||||
# => ["Smashed Cheese", "Smashed Tomato"]
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
double = (x) -> x*2
|
||||
triple = (x) -> x*3
|
||||
addOne = (x) -> x+1
|
||||
|
||||
addOne triple double 2 # same as addOne(triple(double(2)))
|
||||
|
|
@ -0,0 +1 @@
|
|||
(-> -> -> -> 2 )()()()() # => 2
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
((x)->
|
||||
2 + x(-> 5)
|
||||
)((y) -> y()+3)
|
||||
# result: 10
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
CL-USER> (defun add (a b) (+ a b))
|
||||
ADD
|
||||
CL-USER> (add 1 2)
|
||||
3
|
||||
CL-USER> (defun call-it (fn x y)
|
||||
(funcall fn x y))
|
||||
CALL-IT
|
||||
CL-USER> (call-it #'add 1 2)
|
||||
3
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
include "cowgol.coh";
|
||||
|
||||
# In order to pass functions around, you must first define an interface.
|
||||
# This is similar to a delegate in C#; it becomes a function pointer type.
|
||||
# This interface takes two integers and returns one.
|
||||
interface Dyadic(x: int32, y: int32): (r: int32);
|
||||
|
||||
# For a function to be able to be passed around, it must explicitly implement
|
||||
# an interface. Then it has the same type as that interface.
|
||||
# The interface replaces the method's parameter list entirely.
|
||||
sub Add implements Dyadic is
|
||||
r := x + y;
|
||||
end sub;
|
||||
|
||||
# Here are the other basic operators.
|
||||
sub Sub implements Dyadic is r := x - y; end sub;
|
||||
sub Mul implements Dyadic is r := x * y; end sub;
|
||||
sub Div implements Dyadic is r := x / y; end sub;
|
||||
|
||||
# An interface is just like any other type, and the functions that implement
|
||||
# it are first-class values. For example, this code maps the operator
|
||||
# characters to their functions.
|
||||
record Operator is
|
||||
char: uint8;
|
||||
func: Dyadic;
|
||||
end record;
|
||||
|
||||
var operators: Operator[] := {
|
||||
{'+', Add}, {'-', Sub}, {'*', Mul}, {'/', Div},
|
||||
{0, Dyadic}
|
||||
};
|
||||
|
||||
# This is a function that applies such a function to two values
|
||||
sub apply(f: Dyadic, x: int32, y: int32): (r: int32) is
|
||||
r := f(x,y); # the function can be called as normal
|
||||
end sub;
|
||||
|
||||
# And this is a function that applies all the above operators to two values
|
||||
sub showAll(ops: [Operator], x: int32, y: int32) is
|
||||
while ops.char != 0 loop
|
||||
print_i32(x as uint32);
|
||||
print_char(' ');
|
||||
print_char(ops.char);
|
||||
print_char(' ');
|
||||
print_i32(y as uint32);
|
||||
print(" = ");
|
||||
print_i32(apply(ops.func, x, y) as uint32);
|
||||
print_nl();
|
||||
ops := @next ops;
|
||||
end loop;
|
||||
end sub;
|
||||
|
||||
showAll(&operators[0], 84, 42); # example
|
||||
9
Task/Higher-order-functions/D/higher-order-functions-1.d
Normal file
9
Task/Higher-order-functions/D/higher-order-functions-1.d
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
int hof(int a, int b, int delegate(int, int) f) {
|
||||
return f(a, b);
|
||||
}
|
||||
|
||||
void main() {
|
||||
import std.stdio;
|
||||
writeln("Add: ", hof(2, 3, (a, b) => a + b));
|
||||
writeln("Multiply: ", hof(2, 3, (a, b) => a * b));
|
||||
}
|
||||
61
Task/Higher-order-functions/D/higher-order-functions-2.d
Normal file
61
Task/Higher-order-functions/D/higher-order-functions-2.d
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import std.stdio;
|
||||
|
||||
// Test the function argument.
|
||||
string test(U)(string scopes, U func) {
|
||||
string typeStr = typeid(typeof(func)).toString();
|
||||
|
||||
string isFunc = (typeStr[$ - 1] == '*') ? "function" : "delegate";
|
||||
writefln("Hi, %-13s : scope: %-8s (%s) : %s",
|
||||
func(), scopes, isFunc, typeStr );
|
||||
return scopes;
|
||||
}
|
||||
|
||||
// Normal module level function.
|
||||
string aFunction() { return "Function"; }
|
||||
|
||||
// Implicit-Function-Template-Instantiation (IFTI) Function.
|
||||
T tmpFunc(T)() { return "IFTI.function"; }
|
||||
|
||||
// Member in a template.
|
||||
template tmpGroup(T) {
|
||||
T t0(){ return "Tmp.member.0"; }
|
||||
T t1(){ return "Tmp.member.1"; }
|
||||
T t2(){ return "Tmp.member.2"; }
|
||||
}
|
||||
|
||||
// Used for implementing member function at class & struct.
|
||||
template Impl() {
|
||||
static string aStatic() { return "Static Method"; }
|
||||
string aMethod() { return "Method"; }
|
||||
}
|
||||
|
||||
class C { mixin Impl!(); }
|
||||
struct S { mixin Impl!(); }
|
||||
|
||||
void main() {
|
||||
// Nested function.
|
||||
string aNested() {
|
||||
return "Nested";
|
||||
}
|
||||
|
||||
// Bind to a variable.
|
||||
auto variableF = function string() { return "variable.F"; };
|
||||
auto variableD = delegate string() { return "variable.D"; };
|
||||
|
||||
C c = new C;
|
||||
S s;
|
||||
|
||||
"Global".test(&aFunction);
|
||||
"Nested".test(&aNested);
|
||||
"Class".test(&C.aStatic)
|
||||
.test(&c.aMethod);
|
||||
"Struct".test(&S.aStatic)
|
||||
.test(&s.aMethod);
|
||||
"Template".test(&tmpFunc!(string))
|
||||
.test(&tmpGroup!(string).t2);
|
||||
"Binding".test(variableF)
|
||||
.test(variableD);
|
||||
// Literal function/delegate.
|
||||
"Literal".test(function string() { return "literal.F"; })
|
||||
.test(delegate string() { return "literal.D"; });
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
type TFnType = function(x : Float) : Float;
|
||||
|
||||
function First(f : TFnType) : Float;
|
||||
begin
|
||||
Result := f(1) + 2;
|
||||
end;
|
||||
|
||||
function Second(f : Float) : Float;
|
||||
begin
|
||||
Result := f/2;
|
||||
end;
|
||||
|
||||
PrintLn(First(Second));
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
/* Example functions - there are no anonymous functions */
|
||||
proc nonrec square(word n) word: n*n corp
|
||||
proc nonrec cube(word n) word: n*n*n corp
|
||||
|
||||
/* A function that takes another function.
|
||||
* Note how a function is defined as:
|
||||
* proc name(arguments) returntype: [code here] corp
|
||||
* But a function variable is instead defined as:
|
||||
* proc(arguments) returntype name
|
||||
*/
|
||||
proc nonrec do_func(word start, stop; proc(word n) word fn) void:
|
||||
word n;
|
||||
for n from start upto stop do
|
||||
write(fn(n):8)
|
||||
od;
|
||||
writeln()
|
||||
corp
|
||||
|
||||
/* We can then just pass the name of a function as an argument */
|
||||
proc main() void:
|
||||
do_func(1, 10, square);
|
||||
do_func(1, 10, cube)
|
||||
corp
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
func call(f, a, b) {
|
||||
f(a, b)
|
||||
}
|
||||
|
||||
let a = 6
|
||||
let b = 2
|
||||
|
||||
print("f=add, f(\(a), \(b)) = \(call((x, y) => x + y, a, b))")
|
||||
print("f=mul, f(\(a), \(b)) = \(call((x, y) => x * y, a, b))")
|
||||
print("f=div, f(\(a), \(b)) = \(call((x, y) => x / y, a, b))")
|
||||
17
Task/Higher-order-functions/E/higher-order-functions.e
Normal file
17
Task/Higher-order-functions/E/higher-order-functions.e
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
def map(f, list) {
|
||||
var out := []
|
||||
for x in list {
|
||||
out with= f(x)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
? map(fn x { x + x }, [1, "two"])
|
||||
# value: [2, "twotwo"]
|
||||
|
||||
? map(1.add, [5, 10, 20])
|
||||
# value: [6, 11, 21]
|
||||
|
||||
? def foo(x) { return -(x.size()) }
|
||||
> map(foo, ["", "a", "bc"])
|
||||
# value: [0, -1, -2]
|
||||
51
Task/Higher-order-functions/ECL/higher-order-functions.ecl
Normal file
51
Task/Higher-order-functions/ECL/higher-order-functions.ecl
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
//a Function prototype:
|
||||
INTEGER actionPrototype(INTEGER v1, INTEGER v2) := 0;
|
||||
|
||||
INTEGER aveValues(INTEGER v1, INTEGER v2) := (v1 + v2) DIV 2;
|
||||
INTEGER addValues(INTEGER v1, INTEGER v2) := v1 + v2;
|
||||
INTEGER multiValues(INTEGER v1, INTEGER v2) := v1 * v2;
|
||||
|
||||
//a Function prototype using a function prototype:
|
||||
INTEGER applyPrototype(INTEGER v1, actionPrototype actionFunc) := 0;
|
||||
|
||||
//using the Function prototype and a default value:
|
||||
INTEGER applyValue2(INTEGER v1,
|
||||
actionPrototype actionFunc = aveValues) :=
|
||||
actionFunc(v1, v1+1)*2;
|
||||
|
||||
//Defining the Function parameter inline, witha default value:
|
||||
INTEGER applyValue4(INTEGER v1,
|
||||
INTEGER actionFunc(INTEGER v1,INTEGER v2) = aveValues)
|
||||
:= actionFunc(v1, v1+1)*4;
|
||||
INTEGER doApplyValue(INTEGER v1,
|
||||
INTEGER actionFunc(INTEGER v1, INTEGER v2))
|
||||
:= applyValue2(v1+1, actionFunc);
|
||||
|
||||
//producing simple results:
|
||||
OUTPUT(applyValue2(1)); // 2
|
||||
OUTPUT(applyValue2(2)); // 4
|
||||
OUTPUT(applyValue2(1, addValues)); // 6
|
||||
OUTPUT(applyValue2(2, addValues)); // 10
|
||||
OUTPUT(applyValue2(1, multiValues)); // 4
|
||||
OUTPUT(applyValue2(2, multiValues)); // 12
|
||||
OUTPUT(doApplyValue(1, multiValues)); // 12
|
||||
OUTPUT(doApplyValue(2, multiValues)); // 24
|
||||
|
||||
|
||||
|
||||
//A definition taking function parameters which themselves
|
||||
//have parameters that are functions...
|
||||
|
||||
STRING doMany(INTEGER v1,
|
||||
INTEGER firstAction(INTEGER v1,
|
||||
INTEGER actionFunc(INTEGER v1,INTEGER v2)),
|
||||
INTEGER secondAction(INTEGER v1,
|
||||
INTEGER actionFunc(INTEGER v1,INTEGER v2)),
|
||||
INTEGER actionFunc(INTEGER v1,INTEGER v2))
|
||||
:= (STRING)firstAction(v1, actionFunc) + ':' + (STRING)secondaction(v1, actionFunc);
|
||||
|
||||
OUTPUT(doMany(1, applyValue2, applyValue4, addValues));
|
||||
// produces "6:12"
|
||||
|
||||
OUTPUT(doMany(2, applyValue4, applyValue2,multiValues));
|
||||
// produces "24:12"
|
||||
13
Task/Higher-order-functions/ERRE/higher-order-functions.erre
Normal file
13
Task/Higher-order-functions/ERRE/higher-order-functions.erre
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
PROGRAM FUNC_PASS
|
||||
|
||||
FUNCTION ONE(X,Y)
|
||||
ONE=(X+Y)^2
|
||||
END FUNCTION
|
||||
|
||||
FUNCTION TWO(X,Y)
|
||||
TWO=ONE(X,Y)+1
|
||||
END FUNCTION
|
||||
|
||||
BEGIN
|
||||
PRINT(TWO(10,11))
|
||||
END PROGRAM
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
first = fn (F) {
|
||||
F()
|
||||
}
|
||||
|
||||
second = fn () {
|
||||
io.format("hello~n")
|
||||
}
|
||||
|
||||
@public
|
||||
run = fn () {
|
||||
# passing the function specifying the name and arity
|
||||
# arity: the number of arguments it accepts
|
||||
first(fn second:0)
|
||||
|
||||
first(fn () { io.format("hello~n") })
|
||||
|
||||
# holding a reference to the function in a variable
|
||||
F1 = fn second:0
|
||||
F2 = fn () { io.format("hello~n") }
|
||||
|
||||
first(F1)
|
||||
first(F2)
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
import extensions;
|
||||
|
||||
public program()
|
||||
{
|
||||
var first := (f => f());
|
||||
var second := {"second"};
|
||||
console.printLine(first(second))
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
iex(1)> defmodule RC do
|
||||
...(1)> def first(f), do: f.()
|
||||
...(1)> def second, do: :hello
|
||||
...(1)> end
|
||||
{:module, RC,
|
||||
<<70, 79, 82, 49, 0, 0, 4, 224, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 142,
|
||||
131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95
|
||||
, 118, 49, 108, 0, 0, 0, 2, 104, 2, ...>>,
|
||||
{:second, 0}}
|
||||
iex(2)> RC.first(fn -> RC.second end)
|
||||
:hello
|
||||
iex(3)> RC.first(&RC.second/0) # Another expression
|
||||
:hello
|
||||
iex(4)> f = fn -> :world end # Anonymous function
|
||||
#Function<20.54118792/0 in :erl_eval.expr/5>
|
||||
iex(5)> RC.first(f)
|
||||
:world
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
-module(test).
|
||||
-export([first/1, second/0]).
|
||||
|
||||
first(F) -> F().
|
||||
second() -> hello.
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
1> c(tests).
|
||||
{ok, tests}
|
||||
2> tests:first(fun tests:second/0).
|
||||
hello
|
||||
3> tests:first(fun() -> anonymous_function end).
|
||||
anonymous_function
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
>function f(x,a) := x^a-a^x
|
||||
>function dof (f$:string,x) := f$(x,args());
|
||||
>dof("f",1:5;2)
|
||||
[ -1 0 1 0 -7 ]
|
||||
>plot2d("f",1,5;2):
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
procedure use(integer fi, integer a, integer b)
|
||||
print(1,call_func(fi,{a,b}))
|
||||
end procedure
|
||||
|
||||
function add(integer a, integer b)
|
||||
return a + b
|
||||
end function
|
||||
|
||||
use(routine_id("add"),23,45)
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
> let twice f x = f (f x);;
|
||||
|
||||
val twice : ('a -> 'a) -> 'a -> 'a
|
||||
|
||||
> twice System.Math.Sqrt 81.0;;
|
||||
val it : float = 3.0
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
> List.map2 (+) [1;2;3] [3;2;1];;
|
||||
val it : int list = [4; 4; 4]
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
[f:[$0>][@@\f;!\1-]#%]r: { reduce n stack items using the given basis and binary function }
|
||||
|
||||
1 2 3 4 0 4[+]r;!." " { 10 }
|
||||
1 2 3 4 1 4[*]r;!." " { 24 }
|
||||
1 2 3 4 0 4[$*+]r;!. { 30 }
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
USING: io ;
|
||||
IN: rosetacode
|
||||
: argument-function1 ( -- ) "Hello World!" print ;
|
||||
: argument-function2 ( -- ) "Goodbye World!" print ;
|
||||
|
||||
! normal words have to know the stack effect of the input parameters they execute
|
||||
: calling-function1 ( another-function -- ) execute( -- ) ;
|
||||
|
||||
! unlike normal words, inline words do not have to know the stack effect.
|
||||
: calling-function2 ( another-function -- ) execute ; inline
|
||||
|
||||
! Stack effect has to be written for runtime computed values :
|
||||
: calling-function3 ( bool -- ) \ argument-function1 \ argument-function2 ? execute( -- ) ;
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
class Main
|
||||
{
|
||||
// apply given function to two arguments
|
||||
static Int performOp (Int arg1, Int arg2, |Int, Int -> Int| fn)
|
||||
{
|
||||
fn (arg1, arg2)
|
||||
}
|
||||
|
||||
public static Void main ()
|
||||
{
|
||||
echo (performOp (2, 5, |Int a, Int b -> Int| { a + b }))
|
||||
echo (performOp (2, 5, |Int a, Int b -> Int| { a * b }))
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
: square dup * ;
|
||||
: cube dup dup * * ;
|
||||
: map. ( xt addr len -- )
|
||||
0 do 2dup i cells + @ swap execute . loop 2drop ;
|
||||
|
||||
create array 1 , 2 , 3 , 4 , 5 ,
|
||||
' square array 5 map. cr \ 1 4 9 16 25
|
||||
' cube array 5 map. cr \ 1 8 27 64 125
|
||||
:noname 2* 1+ ; array 5 map. cr \ 3 5 7 9 11
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
FUNCTION FUNC3(FUNC1, FUNC2, x, y)
|
||||
REAL, EXTERNAL :: FUNC1, FUNC2
|
||||
REAL :: FUNC3
|
||||
REAL :: x, y
|
||||
|
||||
FUNC3 = FUNC1(x) * FUNC2(y)
|
||||
END FUNCTION FUNC3
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
module FuncContainer
|
||||
implicit none
|
||||
contains
|
||||
|
||||
function func1(x)
|
||||
real :: func1
|
||||
real, intent(in) :: x
|
||||
|
||||
func1 = x**2.0
|
||||
end function func1
|
||||
|
||||
function func2(x)
|
||||
real :: func2
|
||||
real, intent(in) :: x
|
||||
|
||||
func2 = x**2.05
|
||||
end function func2
|
||||
|
||||
end module FuncContainer
|
||||
|
||||
program FuncArg
|
||||
use FuncContainer
|
||||
implicit none
|
||||
|
||||
print *, "Func1"
|
||||
call asubroutine(func1)
|
||||
|
||||
print *, "Func2"
|
||||
call asubroutine(func2)
|
||||
|
||||
contains
|
||||
|
||||
subroutine asubroutine(f)
|
||||
! the following interface is redundant: can be omitted
|
||||
interface
|
||||
function f(x)
|
||||
real, intent(in) :: x
|
||||
real :: f
|
||||
end function f
|
||||
end interface
|
||||
real :: px
|
||||
|
||||
px = 0.0
|
||||
do while( px < 10.0 )
|
||||
print *, px, f(px)
|
||||
px = px + 1.0
|
||||
end do
|
||||
end subroutine asubroutine
|
||||
|
||||
end program FuncArg
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
' FB 1.05.0 Win64
|
||||
|
||||
Function square(n As Integer) As Integer
|
||||
Return n * n
|
||||
End Function
|
||||
|
||||
Function cube(n As Integer) As Integer
|
||||
Return n * n * n
|
||||
End Function
|
||||
|
||||
Sub doCalcs(from As Integer, upTo As Integer, title As String, func As Function(As Integer) As Integer)
|
||||
Print title; " -> ";
|
||||
For i As Integer = from To upTo
|
||||
Print Using "#####"; func(i);
|
||||
Next
|
||||
Print
|
||||
End Sub
|
||||
|
||||
doCalcs 1, 10, "Squares", @square
|
||||
doCalcs 1, 10, "Cubes ", @cube
|
||||
Print
|
||||
Print "Press any key to quit"
|
||||
Sleep
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
cmpFunc = {|a,b| length[a] <=> length[b]}
|
||||
|
||||
a = ["tree", "apple", "bee", "monkey", "z"]
|
||||
sort[a, cmpFunc]
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
lengthCompare[a,b] := length[a] <=> length[b]
|
||||
|
||||
func = getFunction["lengthCompare", 2]
|
||||
a = ["tree", "apple", "bee", "monkey", "z"]
|
||||
sort[a, func]
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
window 1
|
||||
|
||||
dim as pointer functionOneAddress
|
||||
|
||||
def fn FunctionOne( x as long, y as long ) as long = (x + y) ^ 2
|
||||
functionOneAddress = @fn FunctionOne
|
||||
|
||||
def fn FunctionTwo( x as long, y as long ) using functionOneAddress
|
||||
|
||||
print fn FunctionTwo( 12, 12 )
|
||||
|
||||
HandleEvents
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
Eval := function(f, x)
|
||||
return f(x);
|
||||
end;
|
||||
|
||||
Eval(x -> x^3, 7);
|
||||
# 343
|
||||
6
Task/Higher-order-functions/Go/higher-order-functions.go
Normal file
6
Task/Higher-order-functions/Go/higher-order-functions.go
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
package main
|
||||
import "fmt"
|
||||
|
||||
func func1(f func(string) string) string { return f("a string") }
|
||||
func func2(s string) string { return "func2 called with " + s }
|
||||
func main() { fmt.Println(func1(func2)) }
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
first = { func -> func() }
|
||||
second = { println "second" }
|
||||
|
||||
first(second)
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
def first(func) { func() }
|
||||
def second() { println "second" }
|
||||
|
||||
first(this.&second)
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
func1 f = f "a string"
|
||||
func2 s = "func2 called with " ++ s
|
||||
|
||||
main = putStrLn $ func1 func2
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
func f = f 1 2
|
||||
|
||||
main = print $ func (\x y -> x+y)
|
||||
-- output: 3
|
||||
13
Task/Higher-order-functions/Icon/higher-order-functions.icon
Normal file
13
Task/Higher-order-functions/Icon/higher-order-functions.icon
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
procedure main()
|
||||
local lst
|
||||
lst := [10, 20, 30, 40]
|
||||
myfun(callback, lst)
|
||||
end
|
||||
|
||||
procedure myfun(fun, lst)
|
||||
every fun(!lst)
|
||||
end
|
||||
|
||||
procedure callback(arg)
|
||||
write("->", arg)
|
||||
end
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
[ func;
|
||||
print "Hello^";
|
||||
];
|
||||
|
||||
[ call_func x;
|
||||
x();
|
||||
];
|
||||
|
||||
[ Main;
|
||||
call_func(func);
|
||||
];
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
Higher Order Functions is a room.
|
||||
|
||||
To decide which number is (N - number) added to (M - number) (this is addition):
|
||||
decide on N + M.
|
||||
|
||||
To decide which number is multiply (N - number) by (M - number) (this is multiplication):
|
||||
decide on N * M.
|
||||
|
||||
To demonstrate (P - phrase (number, number) -> number) as (title - text):
|
||||
say "[title]: [P applied to 12 and 34]."
|
||||
|
||||
When play begins:
|
||||
demonstrate addition as "Add";
|
||||
demonstrate multiplication as "Mul";
|
||||
end the story.
|
||||
31
Task/Higher-order-functions/J/higher-order-functions-1.j
Normal file
31
Task/Higher-order-functions/J/higher-order-functions-1.j
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
+ / 3 1 4 1 5 9 NB. sum
|
||||
23
|
||||
>./ 3 1 4 1 5 9 NB. max
|
||||
9
|
||||
*./ 3 1 4 1 5 9 NB. lcm
|
||||
180
|
||||
|
||||
+/\ 3 1 4 1 5 9 NB. sum prefix (partial sums)
|
||||
3 4 8 9 14 23
|
||||
|
||||
+/\. 3 1 4 1 5 9 NB. sum suffix
|
||||
23 20 19 15 14 9
|
||||
|
||||
2&% 1 2 3 NB. divide 2 by
|
||||
2 1 0.666667
|
||||
|
||||
%&2 (1 2 3) NB. divide by 2 (need parenthesis to break up list formation)
|
||||
0.5 1 1.5
|
||||
-: 1 2 3 NB. but divide by 2 happens a lot so it's a primitive
|
||||
0.5 1 1.5
|
||||
|
||||
f=: -:@(+ 2&%) NB. one Newton iteration
|
||||
f 1
|
||||
1.5
|
||||
f f 1
|
||||
1.41667
|
||||
|
||||
f^:(i.5) 1 NB. first 5 Newton iterations
|
||||
1 1.5 1.41667 1.41422 1.41421
|
||||
f^:(i.5) 1x NB. rational approximations to sqrt 2
|
||||
1 3r2 17r12 577r408 665857r470832
|
||||
8
Task/Higher-order-functions/J/higher-order-functions-2.j
Normal file
8
Task/Higher-order-functions/J/higher-order-functions-2.j
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
+ conjunction def 'u' -
|
||||
+
|
||||
+ conjunction def 'v' -
|
||||
-
|
||||
* adverb def '10 u y' 11
|
||||
110
|
||||
^ conjunction def '10 v 2 u y' * 11
|
||||
20480
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
public class NewClass {
|
||||
|
||||
public NewClass() {
|
||||
first(new AnEventOrCallback() {
|
||||
public void call() {
|
||||
second();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void first(AnEventOrCallback obj) {
|
||||
obj.call();
|
||||
}
|
||||
|
||||
public void second() {
|
||||
System.out.println("Second");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new NewClass();
|
||||
}
|
||||
}
|
||||
|
||||
interface AnEventOrCallback {
|
||||
public void call();
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
public class ListenerTest {
|
||||
public static void main(String[] args) {
|
||||
JButton testButton = new JButton("Test Button");
|
||||
testButton.addActionListener(new ActionListener(){
|
||||
@Override public void actionPerformed(ActionEvent ae){
|
||||
System.out.println("Click Detected by Anon Class");
|
||||
}
|
||||
});
|
||||
|
||||
testButton.addActionListener(e -> System.out.println("Click Detected by Lambda Listner"));
|
||||
|
||||
// Swing stuff
|
||||
JFrame frame = new JFrame("Listener Test");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.add(testButton, BorderLayout.CENTER);
|
||||
frame.pack();
|
||||
frame.setVisible(true);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
function first (func) {
|
||||
return func();
|
||||
}
|
||||
|
||||
function second () {
|
||||
return "second";
|
||||
}
|
||||
|
||||
var result = first(second);
|
||||
result = first(function () { return "third"; });
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
>>> var array = [2, 4, 5, 13, 18, 24, 34, 97];
|
||||
>>> array
|
||||
[2, 4, 5, 13, 18, 24, 34, 97]
|
||||
|
||||
// return all elements less than 10
|
||||
>>> array.filter(function (x) { return x < 10 });
|
||||
[2, 4, 5]
|
||||
|
||||
// return all elements less than 30
|
||||
>>> array.filter(function (x) { return x < 30 });
|
||||
[2, 4, 5, 13, 18, 24]
|
||||
|
||||
// return all elements less than 100
|
||||
>>> array.filter(function (x) { return x < 100 });
|
||||
[2, 4, 5, 13, 18, 24, 34, 97]
|
||||
|
||||
// multiply each element by 2 and return the new array
|
||||
>>> array.map(function (x) { return x * 2 });
|
||||
[4, 8, 10, 26, 36, 48, 68, 194]
|
||||
|
||||
// sort the array from smallest to largest
|
||||
>>> array.sort(function (a, b) { return a > b });
|
||||
[2, 4, 5, 13, 18, 24, 34, 97]
|
||||
|
||||
// sort the array from largest to smallest
|
||||
>>> array.sort(function (a, b) { return a < b });
|
||||
[97, 34, 24, 18, 13, 5, 4, 2]
|
||||
|
|
@ -0,0 +1 @@
|
|||
DEFINE first == *.
|
||||
|
|
@ -0,0 +1 @@
|
|||
DEFINE second == i.
|
||||
|
|
@ -0,0 +1 @@
|
|||
2 3 [first] second.
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
def foo( filter ):
|
||||
("world" | filter) as $str
|
||||
| "hello \($str)" ;
|
||||
|
||||
# blue is defined here as a filter that adds blue to its input:
|
||||
def blue: "blue \(.)";
|
||||
|
||||
foo( blue ) # prints "hello blue world"
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
def g(f; x; y): [x,y] | f;
|
||||
|
||||
g(add; 2; 3) # => 5
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
def is_even:
|
||||
if floor == . then (. % 2) == 0
|
||||
else error("is_even expects its input to be an integer")
|
||||
end;
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue