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/Function_prototype

View file

@ -0,0 +1,19 @@
Some languages provide the facility to declare functions and subroutines through the use of [[wp:Function prototype|function prototyping]].
;Task:
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
* An explanation of any placement restrictions for prototype declarations
* A prototype declaration for a function that does not require arguments
* A prototype declaration for a function that requires two arguments
* A prototype declaration for a function that utilizes varargs
* A prototype declaration for a function that utilizes optional arguments
* A prototype declaration for a function that utilizes named parameters
* Example of prototype declarations for subroutines or procedures (if these differ from functions)
* An explanation and example of any special forms of prototyping not covered by the above
<br>
Languages that do not provide function prototyping facilities should be omitted from this task.
<br><br>

View file

@ -0,0 +1,37 @@
#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
# An explanation of any placement restrictions for prototype declarations #
PROC VOID no args; # Declare a function with no argument that returns an INTeger #
PROC (INT #a#,INT #b#)VOID two args; # Declare a function with two arguments that returns an INTeger #
MODE VARARGS = UNION(INT,REAL,COMPL);
PROC ([]VARARGS)VOID var args; # An empty parameter list can be used to declare a function that accepts varargs #
PROC (INT, []VARARGS)VOID at least one args; # One mandatory INTeger argument followed by varargs #
MODE OPTINT = UNION(VOID,INT), OPTSTRING=UNION(VOID,STRING); # a function that utilizes optional arguments #
PROC (OPTINT, OPTSTRING)VOID optional arguments;
# A prototype declaration for a function that utilizes named parameters #
MODE KWNAME = STRUCT(STRING name),
KWSPECIES = STRUCT(STRING species),
KWBREED = STRUCT(STRING breed),
OWNER=STRUCT(STRING first name, middle name, last name);
# due to the "Yoneda ambiguity" simple arguments must have an unique operator defined #
OP NAME = (STRING name)KWNAME: (KWNAME opt; name OF opt := name; opt),
SPECIES = (STRING species)KWSPECIES: (KWSPECIES opt; species OF opt := species; opt),
BREED = (STRING breed)KWBREED: (KWBREED opt; breed OF opt := breed; opt);
PROC ([]UNION(KWNAME,KWSPECIES,KWBREED,OWNER) #options#)VOID print pet;
# subroutines, and fuctions are procedures, so have the same prototype declarations #
# An explanation and example of any special forms of prototyping not covered by the above: #
COMMENT
If a function has no arguments, eg f,
then it is not requied to pass it a "vacuum()" to call it, eg "f()" not correct!
Rather is can be called without the () vacuum. eg "f"
A GOTO "label" is equivalent to "PROC VOID label".
END COMMENT
SKIP

View file

@ -0,0 +1,6 @@
function noargs return Integer;
function twoargs (a, b : Integer) return Integer;
-- varargs do not exist
function optionalargs (a, b : Integer := 0) return Integer;
-- all parameters are always named, only calling by name differs
procedure dostuff (a : Integer);

View file

@ -0,0 +1,5 @@
type Box; -- tell Ada a box exists (undefined yet)
type accBox is access Box; -- define a pointer to a box
type Box is record -- later define what a box is
next : accBox; -- including that a box holds access to other boxes
end record;

View file

@ -0,0 +1,4 @@
package Stack is
procedure Push(Object:Integer);
function Pull return Integer;
end Stack;

View file

@ -0,0 +1,13 @@
package body Stack is
procedure Push(Object:Integer) is
begin
-- implementation goes here
end;
function Pull return Integer;
begin
-- implementation goes here
end;
end Stack;

View file

@ -0,0 +1,8 @@
with Stack;
procedure Main is
N:integer:=5;
begin
Push(N);
...
N := Pull;
end Main;

View file

@ -0,0 +1,10 @@
integer f0(void); # No arguments
void f1(integer, real); # Two arguments
real f2(...); # Varargs
void f3(integer, ...); # Varargs
void f4(integer &, text &); # Two arguments (integer and string), pass by reference
integer f5(integer, integer (*)(integer));
# Two arguments: integer and function returning integer and taking one integer argument
integer f6(integer a, real b); # Parameters names are allowed
record f7(void); # Function returning an associative array

View file

@ -0,0 +1,36 @@
#!/usr/bin/hopper
// Archivo Hopper
#include <hopper.h>
#context-free noargs /* Declare a pseudo-function with no argument */
#synon noargs no arguments
#context multiargs /* Declare a pseudo-function with multi arguments */
#proto twoargs(_X_,_Y_) /* Declare a pseudo-function with two arguments. #PROTO need arguments */
main:
no arguments
_two args(2,2) // pseudo-function #proto need "_" sufix
println
{1,2,3,"hola mundo!","\n"}, multiargs
exit(0)
.locals
multiargs:
_PARAMS_={},pushall(_PARAMS_)
[1:3]get(_PARAMS_),stats(SUMMATORY),println
{"Mensaje: "}[4:5]get(_PARAMS_),println
clear(_PARAMS_)
back
twoargs(a,b)
{a}mulby(b)
back
// This function is as useful a s an ashtray on a motorcycle:
no args:
{0}minus(0),kill
back
{0}return

View file

@ -0,0 +1,7 @@
int noargs(); // Declare a function with no arguments that returns an integer
int twoargs(int a,int b); // Declare a function with two arguments that returns an integer
int twoargs(int ,int); // Parameter names are optional in a prototype definition
int anyargs(...); // An ellipsis is used to declare a function that accepts varargs
int atleastoneargs(int, ...); // One mandatory integer argument followed by varargs
template<typename T> T declval(T); //A function template
template<typename ...T> tuple<T...> make_tuple(T...); //Function template using parameter pack (since c++11)

View file

@ -0,0 +1,12 @@
using System;
abstract class Printer
{
public abstract void Print();
}
class PrinterImpl : Printer
{
public override void Print() {
Console.WriteLine("Hello world!");
}
}

View file

@ -0,0 +1,22 @@
using System;
public delegate int IntFunction(int a, int b);
public class Program
{
public static int Add(int x, int y) {
return x + y;
}
public static int Multiply(int x, int y) {
return x * y;
}
public static void Main() {
IntFunction func = Add;
Console.WriteLine(func(2, 3)); //prints 5
func = Multiply;
Console.WriteLine(func(2, 3)); //prints 6
func += Add;
Console.WriteLine(func(2, 3)); //prints 5. Both functions are called, but only the last result is kept.
}
}

View file

@ -0,0 +1,20 @@
//file1.cs
public partial class Program
{
partial void Print();
}
//file2.cs
using System;
public partial class Program
{
partial void Print() {
Console.WriteLine("Hello world!");
}
static void Main() {
Program p = new Program();
p.Print(); //If the implementation above is not written, the compiler will remove this line.
}
}

View file

@ -0,0 +1,5 @@
int noargs(void); /* Declare a function with no argument that returns an integer */
int twoargs(int a,int b); /* Declare a function with two arguments that returns an integer */
int twoargs(int ,int); /* Parameter names are optional in a prototype definition */
int anyargs(); /* An empty parameter list can be used to declare a function that accepts varargs */
int atleastoneargs(int, ...); /* One mandatory integer argument followed by varargs */

View file

@ -0,0 +1,39 @@
*> A subprogram taking no arguments and returning nothing.
PROGRAM-ID. no-args PROTOTYPE.
END PROGRAM no-args.
*> A subprogram taking two 8-digit numbers as arguments, and returning
*> an 8-digit number.
PROGRAM-ID. two-args PROTOTYPE.
DATA DIVISION.
LINKAGE SECTION.
01 arg-1 PIC 9(8).
01 arg-2 PIC 9(8).
01 ret PIC 9(8).
PROCEDURE DIVISION USING arg-1, arg-2 RETURNING ret.
END PROGRAM two-args.
*> A subprogram taking two optional arguments which are 8-digit
*> numbers (passed by reference (the default and compulsory for
*> optional arguments)).
PROGRAM-ID. optional-args PROTOTYPE.
DATA DIVISION.
LINKAGE SECTION.
01 arg-1 PIC 9(8).
01 arg-2 PIC 9(8).
PROCEDURE DIVISION USING OPTIONAL arg-1, OPTIONAL arg-2.
END PROGRAM optional-args.
*> Standard COBOL does not support varargs or named parameters.
*> A function from another language, taking a 32-bit integer by
*> value and returning a 32-bit integer (in Visual COBOL).
PROGRAM-ID. foreign-func PROTOTYPE.
OPTIONS.
ENTRY-CONVENTION some-langauge.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 arg PIC S9(9) USAGE COMP-5.
01 ret PIC S9(9) USAGE COMP-5.
PROCEDURE DIVISION USING arg RETURNING ret.
END PROGRAM foreign-func.

View file

@ -0,0 +1 @@
(declare foo)

View file

@ -0,0 +1,30 @@
(declaim (inline no-args))
(declaim (inline one-arg))
(declaim (inline two-args))
(declaim (inline optional-args))
(defun no-args ()
(format nil "no arguments!"))
(defun one-arg (x)
; inserts the value of x into a string
(format nil "~a" x))
(defun two-args (x y)
; same as function `one-arg', but with two arguments
(format nil "~a ~a" x y))
(defun optional-args (x &optional y) ; optional args are denoted with &optional beforehand
; same as function `two-args', but if y is not given it just prints NIL
(format nil "~a ~a~%" x y))
(no-args) ;=> "no arguments!"
(one-arg 1) ;=> "1"
(two-args 1 "example") ;=> "1 example"
(optional-args 1.0) ;=> "1.0 NIL"
(optional-args 1.0 "example") ;=> "1.0 example"

View file

@ -0,0 +1,47 @@
/// Declare a function with no arguments that returns an integer.
int noArgs();
/// Declare a function with two arguments that returns an integer.
int twoArgs(int a, int b);
/// Parameter names are optional in a prototype definition.
int twoArgs2(int, int);
/// An ellipsis can be used to declare a function that accepts
/// C-style varargs.
int anyArgs(...);
/// One mandatory integer argument followed by C-style varargs.
int atLeastOneArg(int, ...);
/// Declare a function that accepts any number of integers.
void anyInts(int[] a...);
/// Declare a function that accepts D-style varargs.
void anyArgs2(TArgs...)(TArgs args);
/// Declare a function that accepts two or more D-style varargs.
void anyArgs3(TArgs...)(TArgs args) if (TArgs.length > 2);
/// Currently D doesn't support named arguments.
/// One implementation.
int twoArgs(int a, int b) {
return a + b;
}
interface SomeInterface {
void foo();
void foo(int, int);
// Varargs
void foo(...); // C-style.
void foo(int[] a...);
void bar(T...)(T args); // D-style.
// Optional arguments are only supported if a default is provided,
// the default arg(s) has/have to be at the end of the args list.
void foo(int a, int b = 10);
}
void main() {}

View file

@ -0,0 +1,121 @@
program Function_prototype;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TIntArray = TArray<Integer>;
TIntArrayHelper = record helper for TIntArray
const
DEFAULT_VALUE = -1;
// A prototype declaration for a function that does not require arguments
function ToString(): string;
// A prototype declaration for a function that requires two arguments
procedure Insert(Index: Integer; value: Integer);
// A prototype declaration for a function that utilizes varargs
// varargs is not available, but a equivalent is array of const
procedure From(Args: array of const);
//A prototype declaration for a function that utilizes optional arguments
procedure Delete(Index: Integer; Count: Integer = 1);
//A prototype declaration for a function that utilizes named parameters
// Named parameters is not supported in Delphi
//Example of prototype declarations for subroutines or procedures
//(if these differ from functions)
procedure Sqr; //Procedure return nothing
function Averange: double; //Function return a value
end;
{ TIntHelper }
function TIntArrayHelper.Averange: double;
begin
Result := 0;
for var e in self do
Result := Result + e;
Result := Result / Length(self);
end;
procedure TIntArrayHelper.Delete(Index, Count: Integer);
begin
System.Delete(self, Index, Count);
end;
procedure TIntArrayHelper.From(Args: array of const);
var
I, Count: Integer;
begin
Count := Length(Args);
SetLength(self, Count);
if Count = 0 then
exit;
for I := 0 to High(Args) do
with Args[I] do
case VType of
vtInteger:
self[I] := VInteger;
vtBoolean:
self[I] := ord(VBoolean);
vtChar, vtWideChar:
self[I] := StrToIntDef(string(VChar), DEFAULT_VALUE);
vtExtended:
self[I] := Round(VExtended^);
vtString:
self[I] := StrToIntDef(VString^, DEFAULT_VALUE);
vtPChar:
self[I] := StrToIntDef(VPChar, DEFAULT_VALUE);
vtObject:
self[I] := cardinal(VObject);
vtClass:
self[I] := cardinal(VClass);
vtAnsiString:
self[I] := StrToIntDef(string(VAnsiString), DEFAULT_VALUE);
vtCurrency:
self[I] := Round(VCurrency^);
vtVariant:
self[I] := Integer(VVariant^);
vtInt64:
self[I] := Integer(VInt64^);
vtUnicodeString:
self[I] := StrToIntDef(string(VUnicodeString), DEFAULT_VALUE);
end;
end;
procedure TIntArrayHelper.Insert(Index, value: Integer);
begin
system.Insert([value], self, Index);
end;
procedure TIntArrayHelper.Sqr;
begin
for var I := 0 to High(self) do
Self[I] := Self[I] * Self[I];
end;
function TIntArrayHelper.ToString: string;
begin
Result := '[';
for var e in self do
Result := Result + e.ToString + ', ';
Result := Result + ']';
end;
begin
var val: TArray<Integer>;
val.From([1, '2', PI]);
val.Insert(0, -1); // insert -1 at position 0
writeln(' Array: ', val.ToString, ' ');
writeln(' Averange: ', val.Averange: 3: 2);
val.Sqr;
writeln(' Sqr: ', val.ToString);
Readln;
end.

View file

@ -0,0 +1,53 @@
program Function_prototype_class;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Classes;
type
TStringListHelper1 = class helper for TStringList
constructor Create(FileName: TFileName); overload;
end;
TStringListHelper2 = class helper (TStringListHelper1) for TStringList
procedure SaveAndFree(FileName: TFileName);
end;
TStringListHelper3 = class helper (TStringListHelper2) for TStringList
procedure AddDateTime;
end;
{ TStringListHelper1 }
constructor TStringListHelper1.Create(FileName: TFileName);
begin
inherited Create;
if FileExists(FileName) then
LoadFromFile(FileName);
end;
{ TStringListHelper2 }
procedure TStringListHelper2.SaveAndFree(FileName: TFileName);
begin
SaveToFile(FileName);
Free;
end;
{ TStringListHelper3 }
procedure TStringListHelper3.AddDateTime;
begin
self.Add(DateToStr(now));
end;
begin
with TStringList.Create('d:\Text.txt') do
begin
AddDateTime;
SaveAndFree('d:\Text_done.txt');
end;
readln;
end.

View file

@ -0,0 +1,86 @@
// A prototype declaration for a function that does not require arguments
begin_funct(foo); // function as a 'method' with no arguments, no return type
end_funct(foo);
// or
with_funct(foo); // function as a 'method' with no arguments, no return type
// A prototype declaration for a function that requires two arguments
begin_funct(goo)_arg({string}, str1, str2); // two arguments, no return type
end_funct[]; // derived name of function using [], like 'this'
with_funct(goo)_arg({str}, str1, str2); // two arguments, no return type
with_funct(hoo)_param({integer}, i, j); // 'param' posit can be used instead of 'arg'
// A prototype declaration for a function that utilizes varargs
begin_funct(voo)_arg({int}, [vararg], v); // variable number of arguments, no return type, 'int' can be used instead of 'integer'
end_funct[];
begin_funct({int}, voo)_arg({int}, ..., v); // variable number of arguments, with return type
add_var({int}, sum)_v(0);
forall_var(v)_calc([sum]+=[v]);
[voo]_ret([sum]);
end_funct[];
// A prototype declaration for a function that utilizes optional arguments
begin_funct({int}, ooo)_arg(o)_value(1); // optional argument with default value and return type integer
with_funct(ooo)_return([o]); // Can be shortened to [ooo]_ret([0]);
end_funct[];
begin_funct({int}, oxo)_arg(o,u,v)_opt(u)_value(1); // optional argument of second argument with default value and return type integer
[ooo]_ret(1); // the execution has to name arguments or missing in comma-separated list of arguments
end_funct[];
// A prototype declaration for a function that utilizes named parameters
begin_funct({int}, poo)_param({int}, a, b, c); // to enforce named parameters '_param' posit can be used.
[poo]_ret([a]+[b]+[c]);
end_funct[];
exec_funct(poo)_param(a)_value(1)_param(b, c)_value(2, 3) ? me_msg()_funct(poo); ;
begin_funct({int}, poo)_arg({int}, a, b, c); // named parameters can still be used with '_arg' posit.
[poo]_ret([a]+[b]+[c]);
end_funct[];
me_msg()_funct(poo)_arg(a)_value(1)_value(2, 3); // Callee has to figure out unnamed arguments by extraction
// 'exec_' verb is implied before '_funct' action
// Example of prototype declarations for subroutines or procedures (if these differ from functions)
begin_instruct(foo); // instructions are 'methods', no arguments, no return type
end_instruct[foo]; // explicit end of itself
// or
with_instruct(foo); // instructions are 'methods', no arguments, no return type
begin_funct(yoo)_arg(robotMoniker)_param(b); // A '_funct' can be used as a subroutine when missing the '{}' return datatype
// a mix of '_arg' and '_param' posits can be used
with_robot[robotMoniker]_var(sq)_calc([b]^2); // create a variable called 'sq' on robot 'robotMoniker'
end_funct(yoo);
begin_instruct(woo)_arg(robotType)_param(b); // An '_instuct' is only used for subroutines and return datatypes are not accepted
with_robot()_type[robotType]_var(sq)_calc([b]^2); // create a variable called 'sq' on all robots of type 'robotType'
end_funct(woo);
// An explanation and example of any special forms of prototyping not covered by the above
begin_funct({double}, voo)_arg({int}, [numArgs], v); // variable-defined number of arguments, with return type
add_var({int}, sum)_v(0);
add_var({double}, average)_v(0);
for_var(v)_until[numArgs]_calc([sum]+=[v]); // the number of arguments [numArgs] does not have to be number of arguments of v
[voo]_ret([sum]/[numArgs]);
end_funct[];
begin_funct({int}, [numArgsOut], voo)_arg({int}, [numArgsIn], v); // variable-defined number of arguments, with variable-defined number of return types
add_var({int}, sum)_v(0);
add_var({double}, average)_v(0);
for_var(v)_until[numArgsOut]_calc([sum]+=[v]);
[voo]_ret([sum]/[numArgsOut]);
end_funct[];

View file

@ -0,0 +1,23 @@
// A function taking and returning nothing (unit).
val noArgs : unit -> unit
// A function taking two integers, and returning an integer.
val twoArgs : int -> int -> int
// A function taking a ParamPack array of ints, and returning an int. The ParamPack
// attribute is not included in the signature.
val varArgs : int [] -> int
// A function taking an int and a ParamPack array of ints, and returning an
// object of the same type.
val atLeastOnArg : int -> int [] -> int
// A function taking an int Option, and returning an int.
val optionalArg : Option<int> -> int
// Named arguments and the other form of optional arguments are only available on
// methods.
type methodClass =
class
// A method taking an int named x, and returning an int.
member NamedArg : x:int -> int
// A method taking two optional ints in a tuple, and returning an int. The
//optional arguments must be tupled.
member OptionalArgs : ?x:int * ?y:int -> int
end

View file

@ -0,0 +1,37 @@
' FB 1.05.0 Win64
' The position regarding prototypes is broadly similar to that of the C language in that functions,
' sub-routines or operators (unless they have already been fully defined) must be declared before they can be used.
' This is usually done near the top of a file or in a separate header file which is then 'included'.
' Parameter names are optional in declarations. When calling functions, using parameter names
' (as opposed to identifying arguments by position) is not supported.
Type MyType ' needed for operator declaration
i As Integer
End Type
Declare Function noArgs() As Integer ' function with no argument that returns an integer
Declare Function twoArgs(As Integer, As Integer) As Integer ' function with two arguments that returns an integer
Declare Function atLeastOneArg CDecl(As Integer, ...) As Integer ' one mandatory integer argument followed by varargs
Declare Function optionalArg(As Integer = 0) As Integer ' function with a (single) optional argument with default value
Declare Sub noArgs2() ' sub-routine with no argument
Declare Operator + (As MyType, As MyType) As MyType ' operator declaration (no hidden 'This' parameter for MyType)
' FreeBASIC also supports object-oriented programming and here all constructors, destructors,
' methods (function or sub), properties and operators (having a hidden 'This' parameter) must be
' declared within a user defined type and then defined afterwards.
Type MyType2
Public:
Declare Constructor(As Integer)
Declare Destructor()
Declare Sub MySub()
Declare Function MyFunction(As Integer) As Integer
Declare Property MyProperty As Integer
Declare Operator Cast() As String
Private:
i As Integer
End Type

View file

@ -0,0 +1,3 @@
func a() // function with no arguments
func b(x, y int) // function with two arguments
func c(...int) // varargs are called "variadic parameters" in Go.

View file

@ -0,0 +1,2 @@
add :: Int -> Int -> Int
add x y = x+y

View file

@ -0,0 +1 @@
add :: Int->(Int ->(Int->Int))

View file

@ -0,0 +1 @@
printThis = putStrLn("This is being printed.")

View file

@ -0,0 +1,2 @@
add :: Int -> Int -> Int
add x y = x+y

View file

@ -0,0 +1,2 @@
add :: Int -> Int -> Int
add = \x->\y -> x+y

View file

@ -0,0 +1,2 @@
doThis :: Int-> Int-> String
doThis _ _ = "Function with unnamed parameters"

View file

@ -0,0 +1,60 @@
NB. j assumes an unknown name f is a verb of infinite rank
NB. f has infinite ranks
f b. 0
_ _ _
NB. The verb g makes a table.
g=: f/~
NB. * has rank 0
f=: *
NB. indeed, make a multiplication table
f/~ i.5
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 4 8 12 16
NB. g was defined as if f had infinite rank.
g i.5
0 1 4 9 16
NB. f is known to have rank 0.
g=: f/~
NB. Now we reproduce the table
g i.5
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 4 8 12 16
NB. change f to another rank 0 verb
f=: +
NB. and construct an addition table
g i.5
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
NB. f is multiplication at infinite rank
f=: *"_
NB. g, however, has rank 0
g i.5
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 4 8 12 16

View file

@ -0,0 +1,36 @@
// A prototype declaration for a function that does not require arguments
function List() {}
List.prototype.push = function() {
return [].push.apply(this, arguments);
};
List.prototype.pop = function() {
return [].pop.call(this);
};
var l = new List();
l.push(5);
l.length; // 1
l[0]; 5
l.pop(); // 5
l.length; // 0
// A prototype declaration for a function that utilizes varargs
function List() {
this.push.apply(this, arguments);
}
List.prototype.push = function() {
return [].push.apply(this, arguments);
};
List.prototype.pop = function() {
return [].pop.call(this);
};
var l = new List(5, 10, 15);
l.length; // 3
l[0]; 5
l.pop(); // 15
l.length; // 2

View file

@ -0,0 +1,37 @@
// A prototype declaration for a function that does not require arguments
class List {
push() {
return [].push.apply(this, arguments);
}
pop() {
return [].pop.call(this);
}
}
var l = new List();
l.push(5);
l.length; // 1
l[0]; 5
l.pop(); // 5
l.length; // 0
// A prototype declaration for a function that utilizes varargs
class List {
constructor(...args) {
this.push(...args);
}
push() {
return [].push.apply(this, arguments);
}
pop() {
return [].pop.call(this);
}
}
var l = new List(5, 10, 15);
l.length; // 3
l[0]; 5
l.pop(); // 15
l.length; // 2

View file

@ -0,0 +1,9 @@
def Func: # no arguments
def Func(a;b): # two arguments
def Vararg(v):
v as [$a1, $a2] .... # if v is an array, then $a1 will be the first item specified by v, or else null, and so on
def Vararg(a; v):
v as [$a1, $a2] .... # if v is an array, then $a1 will be the first item specified by v, or else null, and so on

View file

@ -0,0 +1,4 @@
julia > function mycompare(a, b)::Cint
(a < b) ? -1 : ((a > b) ? +1 : 0)
end
mycompare (generic function with 1 method)

View file

@ -0,0 +1 @@
julia> mycompare_c = @cfunction(mycompare, Cint, (Ref{Cdouble}, Ref{Cdouble}))

View file

@ -0,0 +1,35 @@
// version 1.0.6
interface MyInterface {
fun foo() // no arguments, no return type
fun goo(i: Int, j: Int) // two arguments, no return type
fun voo(vararg v: Int) // variable number of arguments, no return type
fun ooo(o: Int = 1): Int // optional argument with default value and return type Int
fun roo(): Int // no arguments with return type Int
val poo: Int // read only property of type Int
}
abstract class MyAbstractClass {
abstract fun afoo() // abstract member function, no arguments or return type
abstract var apoo: Int // abstract read/write member property of type Int
}
class Derived : MyAbstractClass(), MyInterface {
override fun afoo() {}
override var apoo: Int = 0
override fun foo() {}
override fun goo(i: Int, j: Int) {}
override fun voo(vararg v: Int) {}
override fun ooo(o: Int): Int = o // can't specify default argument again here but same as in interface
override fun roo(): Int = 2
override val poo: Int = 3
}
fun main(args: Array<String>) {
val d = Derived()
println(d.apoo)
println(d.ooo()) // default argument of 1 inferred
println(d.roo())
println(d.poo)
}

View file

@ -0,0 +1,15 @@
function Func() -- Does not require arguments
return 1
end
function Func(a,b) -- Requires arguments
return a + b
end
function Func(a,b) -- Arguments are optional
return a or 4 + b or 2
end
function Func(a,...) -- One argument followed by varargs
return a,{...} -- Returns both arguments, varargs as table
end

View file

@ -0,0 +1,8 @@
function noargs(): int = ? ;;
function twoargs(x:int, y:int): int = ? ;;
/* underscore means ignore and is not bound to lexical scope */
function twoargs(_:bool, _:bool): int = ? ;;
function anyargs(xs: ...): int = ? ;;
function plusargs(x:int, xs: ...): int = ? ;;

View file

@ -0,0 +1,13 @@
Module Check {
Module MyBeta (a) {
Print "MyBeta", a/2
}
Module TestMe {
Module Beta (x) {
Print "TestMeBeta", x
}
Beta 100
}
TestMe ; Beta as MyBeta
}
Check

View file

@ -0,0 +1,45 @@
Module Check {,
\\ make an event object
\\ with a prototype signature
\\ first parameter is numeric/object by value, and second is by reference
Event Alfa {
Read x, &z
}
\\ make a function with same signature
Function ServiceAlfa {
read a, &b
b+=a
}
\\ add function to event
Event Alfa new &ServiceAlfa()
\\ call event in this module
var=30
Call Event Alfa, 10, &var
Print var=40
\\ make a local module, and pass event by value
Module checkinside (ev) {
\\ ev is a copy of Alfa
m=10
call event ev, 4, &m
Print m=14
\\ clear functions from ev
Event ev Clear
\\ we can call it again, but nothing happen
call event ev, 4, &m
Print m=14
}
checkinside Alfa
\\ so now we call Alfa
Call Event Alfa, 10, &var
Print var=50
Event Alfa Hold
\\ calling do nothing, because of Hold state
Call Event Alfa, 10, &var
Event Alfa Release
Call Event Alfa, 10, &var
Print var=60
}
Check

View file

@ -0,0 +1,51 @@
Module Check {,
\\ make an event object
\\ with a prototype signature
\\ first parameter is numeric/object by value, and second is by reference
Event Alfa {
Read x, &z
}
\\ make a function with same signature
\\ but here prepared to used with current module visibility
m=0
Function ServiceAlfa {
\ this code "see" m variable
\\ we have to use new, to make new a, b for sure
read new a, &b
b+=a
m++
}
\\ add function to event, making reference as local to module
Event Alfa new Lazy$(&ServiceAlfa())
\\ call event in this module
var=30
Call Event Alfa, 10, &var
Print var=40
\\ make a local module, and pass event by value
Module checkinside (ev) {
\\ ev is a copy of Alfa
m=10
call event ev, 4, &m
Print m=14
\\ clear functions from ev
Event ev Clear
\\ we can call it again, but nothing happen
call event ev, 4, &m
Print m=14
}
checkinside Alfa
\\ so now we call Alfa
Call Event Alfa, 10, &var
Print var=50
Event Alfa Hold
\\ calling do nothing, because of Hold state
Call Event Alfa, 10, &var
Event Alfa Release
Call Event Alfa, 10, &var
Print var=60
Print m=4 ' 4 times called ServiceAlfa
}
Check

View file

@ -0,0 +1,50 @@
Module Check {,
\\ make an event object
\\ with a prototype signature
\\ first parameter is numeric/object by value, and second is by reference
Event Alfa {
Read x, &z
}
\\ make a group function with same signature
Group IamStatic {
m=0
Function ServiceAlfa(a, &b) {
b+=a
.m++
}
}
\\ add function to event, making reference as local to module
Event Alfa new &IamStatic.ServiceAlfa()
\\ call event in this module
var=30
Call Event Alfa, 10, &var
Print var=40
\\ make a local module, and pass event by value
Module checkinside (ev) {
\\ ev is a copy of Alfa
m=10
call event ev, 4, &m
Print m=14
\\ clear functions from ev
Event ev Clear
\\ we can call it again, but nothing happen
call event ev, 4, &m
Print m=14
}
checkinside Alfa
\\ so now we call Alfa
Call Event Alfa, 10, &var
Print var=50
Event Alfa Hold
\\ calling do nothing, because of Hold state
Call Event Alfa, 10, &var
Event Alfa Release
Call Event Alfa, 10, &var
Print var=60
Print IamStatic.m=4 ' 4 times called IamStatic.ServiceAlfa
}
Check

View file

@ -0,0 +1,17 @@
# Procedure declarations. All are named
proc noargs(): int
proc twoargs(a, b: int): int
proc anyargs(x: varargs[int]): int
proc optargs(a, b: int = 10): int
# Usage
discard noargs()
discard twoargs(1,2)
discard anyargs(1,2,3,4,5,6,7,8)
discard optargs(5)
# Procedure definitions
proc noargs(): int = echo "noargs"
proc twoargs(a, b: int): int = echo "twoargs"
proc anyargs(x: varargs[int]): int = echo "anyargs"
proc optargs(a: int, b = 10): int = echo "optargs"

View file

@ -0,0 +1,24 @@
(* Usually prototype declarations are put in an interface file,
a file with .mli filename extension *)
(* A prototype declaration for a function that does not require arguments *)
val no_arg : unit -> unit
(* A prototype declaration for a function that requires two arguments *)
val two_args : int -> int -> unit
(* A prototype declaration for a function that utilizes optional arguments *)
val opt_arg : ?param:int -> unit -> unit
(* in this case we add a unit parameter in order to omit the argument,
because ocaml supports partial application *)
(* A prototype declaration for a function that utilizes named parameters *)
val named_arg : param1:int -> param2:int -> unit
(* An explanation and example of any special forms of prototyping not covered by the above *)
(* A prototype declaration for a function that requires a function argument *)
val fun_arg : (int -> int) -> unit
(* A prototype declaration for a function with polymorphic argument *)
val poly_arg : 'a -> unit

View file

@ -0,0 +1 @@
Method new: myMethod

View file

@ -0,0 +1,37 @@
'DECLARE FUNCTION' ABBREVIATED TO '!'
! f() ' a procedure with no params
! f(int a) ' with 1 int param
! f(int *a) ' with 1 int pointer param
! f(int a, int b, inc c) ' with 3 int params
! f(int a,b,c) ' compaction with 3 int params
! f(string s, int a,b) ' with 1 string and 2 int params
! f() as string ' function returning a string
! f(string s) as string ' with 1 string param
! *f(string s) as string ' as a function pointer: @f=address
! f(string s, optional i) ' with opptional param
! f(string s = "Hello") ' optional param with default value
! f(int n, ...) ' 1 specific param and varargs
! f(...) ' any params or none
'TRADITIONAL BASIC DECLARATIONS
declare sub f( s as string, i as long, j as long) ' byref by default
declare function f( byref s as string, byval i as long, byval j as long) as string
'C-STYLE DECLARATIONS
void f(string *s, long i, long j)
string f(string *s, long i, long j)
'BLOCK DIRECTIVES FOR FUNCTION PROTOTYPES:
extern ' shareable stdcall functions
extern lib "xyz.dll" ' for accessing functions in xyz Dynamic Link Library
extern export ' functions to be exported if this is a DLL
extern virtual ' for accssing interfaces and other virtual classes
end extern ' revert to internal function mode

View file

@ -0,0 +1,2 @@
long
foo(GEN a, GEN b)

View file

@ -0,0 +1,3 @@
/*
GP;install("foo","LGG","bar","./filename.gp.so");
*/

View file

@ -0,0 +1,3 @@
/*
GP;install("foo","LDGDG","bar","./filename.gp.so");
*/

View file

@ -0,0 +1,3 @@
/*
GP;install("foo","s*","bar","./filename.gp.so");
*/

View file

@ -0,0 +1,7 @@
declare s1 entry;
declare s2 entry (fixed);
declare s3 entry (fixed, float);
declare f1 entry returns (fixed);
declare f2 entry (float) returns (float);
declare f3 entry (character(*), character(*)) returns (character (20));

View file

@ -0,0 +1,4 @@
sub noargs(); # Declare a function with no arguments
sub twoargs($$); # Declare a function with two scalar arguments. The two sigils act as argument type placeholders
sub noargs :prototype(); # Using the :attribute syntax instead
sub twoargs :prototype($$);

View file

@ -0,0 +1,7 @@
-->
<span style="color: #008080;">forward</span> <span style="color: #008080;">function</span> <span style="color: #000000;">noargs</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- Declare a function with no arguments</span>
<span style="color: #008080;">forward</span> <span style="color: #008080;">procedure</span> <span style="color: #000000;">twoargs</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Declare a procedure with two arguments</span>
<span style="color: #008080;">forward</span> <span style="color: #008080;">procedure</span> <span style="color: #000000;">twoargs</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*b*/</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Parameter names are optional in forward (and actual) definitions</span>
<span style="color: #008080;">forward</span> <span style="color: #008080;">function</span> <span style="color: #000000;">anyargs</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- varargs are [best/often] handled as a (single) sequence in Phix</span>
<span style="color: #008080;">forward</span> <span style="color: #008080;">function</span> <span style="color: #000000;">atleastonearg</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">...);</span> <span style="color: #000080;font-style:italic;">-- Default makes args optional (== actual defn)</span>
<!--

View file

@ -0,0 +1,77 @@
;Forward procedure declare defined with no arguments and that returns a string
Declare.s booTwo()
;Forward procedure declare defined with two arguments and that returns a float
Declare.f moo(x.f, y.f)
;Forward procedure declare with two arguments and an optional argument and that returns a float
Declare.f cmoo(x.f, y.f, m.f = 0)
;*** The following three procedures are defined before their first use.
;Procedure defined with no arguments and that returns a string
Procedure.s boo(): ProcedureReturn "boo": EndProcedure
;Procedure defined with two arguments and that returns an float
Procedure.f aoo(x.f, y.f): ProcedureReturn x + y: EndProcedure
;Procedure defined with two arguments and an optional argument and that returns a float
Procedure.f caoo(x.f, y.f, m.f = 1): ProcedureReturn (x + y) * m: EndProcedure
;ProtoType defined for any function with no arguments and that returns a string
Prototype.s showString()
;Prototype defined for any function with two float arguments and that returns a float
Prototype.f doMath(x.f, y.f)
;ProtoType defined for any function with two float arguments and an optional float argument and that returns a float
Prototype.f doMathWithOpt(x.f, y.f, m.f = 0)
Define a.f = 12, b.f = 5, c.f = 9
Define proc_1.showString, proc_2.doMath, proc_3.doMathWithOpt ;using defined ProtoTypes
If OpenConsole("ProtoTypes and Forward Declarations")
PrintN("Forward Declared procedures:")
PrintN(boo())
PrintN(StrF(a, 2) + " * " + StrF(b, 2) + " = " + StrF(moo(a, b), 2))
PrintN(StrF(a, 2) + " * " + StrF(b, 2) + " + " + StrF(c, 2) + " = " + StrF(cmoo(a, b, c), 2))
PrintN(StrF(a, 2) + " * " + StrF(b, 2) + " = " + StrF(cmoo(a, b), 2))
;set pointers to second set of functions
proc_1 = @boo()
proc_2 = @aoo()
proc_3 = @caoo()
PrintN("ProtoTyped procedures (set 1):")
PrintN(proc_1())
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " = " + StrF(proc_2(a, b), 2))
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " ? " + StrF(c, 2) + " = " + StrF(proc_3(a, b, c), 2))
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " = " + StrF(proc_3(a, b), 2))
;set pointers to second set of functions
proc_1 = @booTwo()
proc_2 = @moo()
proc_3 = @cmoo()
PrintN("ProtoTyped procedures (set 2):")
PrintN(proc_1())
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " = " + StrF(proc_2(a, b), 2))
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " ? " + StrF(c, 2) + " = " + StrF(proc_3(a, b, c), 2))
PrintN(StrF(a, 2) + " ? " + StrF(b, 2) + " = " + StrF(proc_3(a, b), 2))
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
;*** If the forward Declaration above are not used then the following Procedure
;definitions each have to be placed before the call to the respective procedure.
;Procedure defined with no arguments and that returns a string
Procedure.s booTwo()
ProcedureReturn "booTwo"
EndProcedure
;Procedure defined with two arguments and that returns an float
Procedure.f moo(x.f, y.f)
ProcedureReturn x * y
EndProcedure
;Procedure defined with two arguments and an optional argument and that returns an float
Procedure.f cmoo(x.f, y.f, m.f = 0)
ProcedureReturn (x * y) + m
EndProcedure

View file

@ -0,0 +1,5 @@
forward is fibonacci ( n --> n )
[ dup 2 < if done
dup 1 - fibonacci
swap 2 - fibonacci + ] resolves fibonacci ( n --> n )

View file

@ -0,0 +1,11 @@
#lang racket
(define (no-arg) (void))
(define (two-args a b) (void)) ;arguments are always named
(define (varargs . args) (void)) ;the extra arguments are stored in a list
(define (varargs2 a . args) (void)) ;one obligatory argument and the rest are contained in the list
(define (optional-arg (a 5)) (void)) ;a defaults to 5

View file

@ -0,0 +1,2 @@
(provide (contract-out
[two-args (integer? integer? . -> . any)]))

View file

@ -0,0 +1,4 @@
#lang typed/racket
(: two-args (Integer Integer -> Any))
(define (two-args a b) (void))

View file

@ -0,0 +1 @@
sub foo ( --> Int) {...}

View file

@ -0,0 +1 @@
sub foo (@, &:(Str --> Int)) {...}

View file

@ -0,0 +1 @@
sub foo (@, $ --> Int) {...}

View file

@ -0,0 +1 @@
sub foo ($, *@ --> Int) {...}

View file

@ -0,0 +1 @@
sub foo ($, $?, $ = 42 --> Int) {...}

View file

@ -0,0 +1 @@
sub foo ($, :$faster, :$cheaper --> Int) {...}

View file

@ -0,0 +1 @@
sub foo ($, $ --> Nil) {...}

View file

@ -0,0 +1 @@
sub foo ($, :$option, *% --> Int) {...}

View file

@ -0,0 +1 @@
sub foo ($, :$option! --> Int) {...}

View file

@ -0,0 +1 @@
sub foo ([$, @]) {...}

View file

@ -0,0 +1,8 @@
define('multiply(a,b)') :(mul_end)
multiply multiply = a * b :(return)
mul_end
* Test
output = multiply(10.1,12.2)
output = multiply(10,12)
end

View file

@ -0,0 +1,21 @@
define('multiply(a,b)')
*
* Assume lots more code goes here.
*
:(test)
*
* MORE CODE!
*
multiply multiply = a * b :(return)
*
* MORE CODE!
*
test
output = multiply(10.1,12.2)
output = multiply(10,12)
end

View file

@ -0,0 +1,10 @@
define('multiply(a,b)acc1,acc2','mult_impl') :(mult_end)
mult_impl acc1 = a
acc2 = b
multiply = acc1 * acc2 :(return)
mult_end
* Test
output = multiply(10.1,12.2)
output = multiply(10,12)
end

View file

@ -0,0 +1,5 @@
var factorial // forward declaration
factorial = Fn.new { |n| (n <= 1) ? 1 : factorial.call(n-1) * n }
System.print(factorial.call(5))

View file

@ -0,0 +1,24 @@
fcn{"Hello World"} // no expected args
fcn(){"Hello World"} // ditto
fcn{vm.arglist}(1,2) // ask the VM for the passed in args -->L(1,2)
fcn f(a,b){a+b} // fcn(1,2,3) works just fine
fcn f(args){}(1,2,3) //args = 1
fcn(args){vm.arglist.sum()}(1,2,3) //-->6
fcn(a=1,b=2){vm.arglist}() //-->L(1,2)
fcn(a=1,b=2){vm.arglist}(5) //-->L(5,2)
fcn(a=1,b){vm.arglist}() //-->L(1), error if you try to use b
fcn(a,b=2){vm.arglist}(5) //-->L(5,2)
fcn(a,b=2,c){vm.arglist}(1) //-->L(1,2)
fcn(){vm.nthArg(1)}(5,6) //-->6
fcn{vm.numArgs}(1,2,3,4,5,6,7,8,9) //-->9
fcn{vm.argsMatch(...)} // a somewhat feeble attempt arg pattern matching based on type (vs value)
// you can do list assignment in the prototype:
fcn(a,[(b,c)],d){vm.arglist}(1,L(2,3,4),5) //-->L(1,L(2,3,4),5)
fcn(a,[(b,c)],d){"%s,%s,%s,%s".fmt(a,b,c,d)}(1,L(2,3,4),5) //-->1,2,3,5
// no type enforcement but you can give a hint to the compiler
fcn([Int]n){n.sin()} //--> syntax error as Ints don't do sin