This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,3 @@
Pass a function ''as an argument'' to another function.
C.f. [[First-class functions]]

View file

@ -0,0 +1,2 @@
---
note: Programming language concepts

View file

@ -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)))
)

View file

@ -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);
}
}
}

View 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;

View 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;

View 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;
}

View file

@ -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

View file

@ -0,0 +1,9 @@
f(x) {
return x
}
g(x, y) {
msgbox %x%
msgbox %y%
}
g(f("RC Function as an Argument AHK implementation"), "Non-function argument")
return

View file

@ -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)

View file

@ -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
)
);

View file

@ -0,0 +1,5 @@
add = { a, b | a + b }
doit = { f, a, b | f a, b }
p doit ->add 1 2 #prints 3

View file

@ -0,0 +1,2 @@
blsq ) {1 2 3 4}{5.+}m[
{6 7 8 9}

View file

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

View 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;
}

View file

@ -0,0 +1,38 @@
using System;
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)
{
return f(a, b);
}
static void Main()
{
int a = 6;
int b = 2;
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));
}
}

View file

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

View file

@ -0,0 +1,18 @@
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;
Console.WriteLine("f=Add, f({0}, {1}) = {2}", a, b, Call((x, y) => x + y, a, b));
Console.WriteLine("f=Mul, f({0}, {1}) = {2}", a, b, Call((x, y) => x * y, a, b));
Console.WriteLine("f=Div, f({0}, {1}) = {2}", a, b, Call((x, y) => x / y, a, b));
}
}

View file

@ -0,0 +1,9 @@
void myFuncSimple( void (*funcParameter)(void) )
{
/* ... */
(*funcParameter)(); /* Call the passed function. */
funcParameter(); /* Same as above with slight different syntax. */
/* ... */
}

View file

@ -0,0 +1,5 @@
void funcToBePassed(void);
/* ... */
myFuncSimple(&funcToBePassed);

View 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. */
/* ... */
}

View file

@ -0,0 +1,7 @@
double* funcToBePassed(long* parameter);
/* ... */
int* outInt;
outInt = myFuncComplex(&funcToBePassed);

View file

@ -0,0 +1,5 @@
int* (*funcPointer)( double* (*funcParameter)(long* parameter) );
/* ... */
funcPointer = &myFuncComplex;

View file

@ -0,0 +1,2 @@
map f [x:xs] = [f x:map f xs]
map f [] = []

View file

@ -0,0 +1,3 @@
incr x = x + 1
Start = map incr [1..10]

View file

@ -0,0 +1 @@
Start = map (\x -> x + 1) [1..10]

View file

@ -0,0 +1 @@
Start = map ((+) 1) [1..10]

View file

@ -0,0 +1,7 @@
(defn append-hello [s]
(str "Hello " s))
(defn modify-string [f s]
(f s))
(println (modify-string append-hello "World!"))

View file

@ -0,0 +1 @@
double = [1,2,3].map (x) -> x*2

View file

@ -0,0 +1,3 @@
fn = -> return 8
sum = (a, b) -> a() + b()
sum(fn, fn) # => 16

View file

@ -0,0 +1,7 @@
bowl = ["Cheese", "Tomato"]
smash = (ingredient) ->
return "Smashed #{ingredient}"
contents = smash ingredient for ingredient in bowl
# => ["Smashed Cheese", "Smashed Tomato"]

View file

@ -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)))

View file

@ -0,0 +1 @@
(-> -> -> -> 2 )()()()() # => 2

View file

@ -0,0 +1,4 @@
((x)->
2 + x(-> 5)
)((y) -> y()+3)
# result: 10

View file

@ -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

View 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));
}

View 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"; });
}

View file

@ -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));

View 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]

View file

@ -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)
}

View file

@ -0,0 +1,5 @@
-module(test).
-export([first/1, second/0]).
first(F) -> F().
second() -> hello.

View file

@ -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

View file

@ -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):

View file

@ -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)

View file

@ -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 }

View file

@ -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( -- ) ;

View file

@ -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 }))
}
}

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -0,0 +1,6 @@
Eval := function(f, x)
return f(x);
end;
Eval(x -> x^3, 7);
# 343

View 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)) }

View file

@ -0,0 +1,4 @@
first = { func -> func() }
second = { println "second" }
first(second)

View file

@ -0,0 +1,4 @@
def first(func) { func() }
def second() { println "second" }
first(this.&second)

View file

@ -0,0 +1,4 @@
func1 f = f "a string"
func2 s = "func2 called with " ++ s
main = putStrLn $ func1 func2

View file

@ -0,0 +1,4 @@
func f = f 1 2
main = print $ func (\x y -> x+y)
-- output: 3

View 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

View file

@ -0,0 +1,11 @@
[ func;
print "Hello^";
];
[ call_func x;
x();
];
[ Main;
call_func(func);
];

View file

@ -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 (N - number) multiplied 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.

View file

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

View 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

View file

@ -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();
}

View file

@ -0,0 +1,10 @@
function first (func) {
return func();
}
function second () {
return "second";
}
var result = first(second);
result = first(function () { return "third"; });

View file

@ -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]

View file

@ -0,0 +1 @@
DEFINE first == *.

View file

@ -0,0 +1 @@
DEFINE second == i.

View file

@ -0,0 +1 @@
2 3 [first] second.

View file

@ -0,0 +1,8 @@
to printstuff
print "stuff
end
to runstuff :proc
run :proc
end
runstuff "printstuff ; stuff
runstuff [print [also stuff]] ; also stuff

View file

@ -0,0 +1,3 @@
a = function() return 1 end
b = function(r) print( r() ) end
b(a)

View file

@ -0,0 +1,11 @@
fn second =
(
print "Second"
)
fn first func =
(
func()
)
first second

View file

@ -0,0 +1,4 @@
PassFunc[f_, g_, h_, x_] := f[g[x]*h[x]]
PassFunc[Tan, Cos, Sin, x]
% /. x -> 0.12
PassFunc[Tan, Cos, Sin, 0.12]

View file

@ -0,0 +1,3 @@
Tan[Cos[x] Sin[x]]
0.119414
0.119414

View file

@ -0,0 +1,6 @@
callee(n) := (print(sconcat("called with ", n)), n + 1)$
caller(f, n) := sum(f(i), i, 1, n)$
caller(callee, 3);
"called with 1"
"called with 2"
"called with 3"

View file

@ -0,0 +1,5 @@
def calcit(expr v, s) = scantokens(s & decimal v) enddef;
t := calcit(100.4, "sind");
show t;
end

View file

@ -0,0 +1,19 @@
MODULE Proc EXPORTS Main;
IMPORT IO;
TYPE Proc = PROCEDURE();
PROCEDURE Second() =
BEGIN
IO.Put("Second procedure.\n");
END Second;
PROCEDURE First(proc: Proc) =
BEGIN
proc();
END First;
BEGIN
First(Second);
END Proc.

View file

@ -0,0 +1,9 @@
function first($func) {
return $func();
}
function second() {
return 'second';
}
$result = first('second');

View file

@ -0,0 +1,5 @@
function first($func) {
return $func();
}
$result = first(function() { return 'second'; });

View file

@ -0,0 +1,27 @@
sub another {
# take a function and a value
my $func = shift;
my $val = shift;
# call the function with the value as argument
return $func->($val);
};
sub reverser {
return scalar reverse shift;
};
# pass named coderef
print another \&reverser, 'data';
# pass anonymous coderef
print another sub {return scalar reverse shift}, 'data';
# if all you have is a string and you want to act on that,
# set up a dispatch table
my %dispatch = (
square => sub {return shift() ** 2},
cube => sub {return shift() ** 3},
rev => \&reverser,
);
print another $dispatch{$_}, 123 for qw(square cube rev);

View file

@ -0,0 +1,8 @@
sub apply (&@) { # use & as the first item in a prototype to take bare blocks like map and grep
my ($sub, @ret) = @_; # this function applies a function that is expected to modify $_ to a list
$sub->() for @ret; # it allows for simple inline application of the s/// and tr/// constructs
@ret
}
print join ", " => apply {tr/aeiou/AEIOU/} qw/one two three four/;
# OnE, twO, thrEE, fOUr

View file

@ -0,0 +1,7 @@
sub first {shift->()}
sub second {'second'}
print first \&second;
print first sub{'sub'};

View file

@ -0,0 +1,33 @@
: (de first (Fun)
(Fun) )
-> first
: (de second ()
"second" )
-> second
: (first second)
-> "second"
: (de add (A B)
(+ A B) )
-> add
: (add 1 2)
-> 3
: (de call-it (Fun X Y)
(Fun X Y) )
-> call-it
: (call-it add 1 2)
-> 3
: (mapcar inc (1 2 3 4 5))
-> (2 3 4 5 6)
: (mapcar + (1 2 3) (4 5 6))
-> (5 7 9)
: (mapcar add (1 2 3) (4 5 6))
-> (5 7 9)

View file

@ -0,0 +1,4 @@
first(Predicate):-Predicate.
second(Argument):-print(Argument).
:-first(second('Hello World!')).

View file

@ -0,0 +1,7 @@
def first(function):
return function()
def second():
return "second"
result = first(second)

View file

@ -0,0 +1 @@
result = first(lambda: "second")

View file

@ -0,0 +1,6 @@
f <- function(f0) f0(pi) # calc. the function in pi
tf <- function(x) x^pi # a func. just to test
print(f(sin))
print(f(cos))
print(f(tf))

View file

@ -0,0 +1,21 @@
/*REXX program demonstrates passing a function as a name to a function.*/
n=3735928559
funcName='fib' ; q= 10; call someFunk funcName, q; call tell
funcName='fact' ; q= 6; call someFunk funcName, q; call tell
funcName='square' ; q= 13; call someFunk funcName, q; call tell
funcName='cube' ; q= 3; call someFunk funcName, q; call tell
q=721; call someFunk 'reverse',q; call tell
say copies('',30) /*display a nice separator fence.*/
say 'done as' d2x(n)"." /*prove that var N still intact. */
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────subroutines─────────────────────────*/
cube: return n**3
fact: !=1; do j=2 to n; !=!*j; end; return !
reverse: return 'REVERSE'(n)
someFunk: procedure; arg ?,n; signal value (?); say result 'result'; return
square: return n**2
tell: say right(funcName'('q") = ",20) result; return
fib: if n==0 | n==1 then return n; _=0; a=0; b=1
do j=2 to n; _=a+b; a=b; b=_; end; return _

View file

@ -0,0 +1,4 @@
#lang racket/base
(define (add f g x)
(+ (f x) (g x)))
(add sin cos 10)

View file

@ -0,0 +1,7 @@
succ = proc{|x| x+1}
def to2(&f)
f[2]
end
to2(&succ) #=> 3
to2{|x| x+1} #=> 3

View file

@ -0,0 +1,9 @@
def succ(n)
n+1
end
def to2(m)
m[2]
end
meth = method(:succ)
to2(meth) #=> 3

View file

@ -0,0 +1 @@
def functionWithAFunctionArgument(x : int, y : int, f : (int, int) => int) = f(x,y)

View file

@ -0,0 +1 @@
functionWithAFunctionArgument(3, 5, {(x, y) => x + y}) // returns 8

View file

@ -0,0 +1,4 @@
> (define (func1 f) (f "a string"))
> (define (func2 s) (string-append "func2 called with " s))
> (begin (display (func1 func2)) (newline))
func2 called with a string

View file

@ -0,0 +1,3 @@
> (define (func f) (f 1 2))
> (begin (display (func (lambda (x y) (+ x y)))) (newline))
3

View file

@ -0,0 +1,3 @@
first := [ :f | f value ].
second := [ 'second' ].
Transcript show: (first value: second).

View file

@ -0,0 +1,2 @@
function := [:x | x * 3 - 1].
#(1 1 2 3 5 8) collect: function.

View file

@ -0,0 +1,6 @@
# this procedure executes its argument:
proc demo {function} {
$function
}
# for example:
demo bell

View file

@ -0,0 +1,19 @@
# This procedure executes its argument with an extra argument of "2"
proc demoFrag {fragment} {
{*}$fragment 2
}
# This procedure executes its argument in the context of its caller, which is
# useful for scripts so they get the right variable resolution context
proc demoScript {script} {
uplevel 1 $script
}
# Examples...
set chan stderr
demoFrag [list puts $chan]
demoFrag {
apply {x {puts [string repeat ? $x]}}
}
demoScript {
parray tcl_platform
}