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,5 @@
---
category:
- Functions and subroutines
- Simple
from: http://rosettacode.org/wiki/Call_a_function

View file

@ -0,0 +1,21 @@
;Task:
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
:*   Calling a function that requires no arguments
:*   Calling a function with a fixed number of arguments
:*   Calling a function with [[Optional parameters|optional arguments]]
:*   Calling a function with a [[Variadic function|variable number of arguments]]
:*   Calling a function with [[Named parameters|named arguments]]
:*   Using a function in statement context
:*   Using a function in [[First-class functions|first-class context]] within an expression
:*   Obtaining the return value of a function
:*   Distinguishing built-in functions and user-defined functions
:*   Distinguishing subroutines and functions
;*   Stating whether arguments are [[:Category:Parameter passing|passed]] by value or by reference
;*   Is partial application possible and how
<br>
This task is ''not'' about [[Function definition|defining functions]].
<br><bR>

View file

@ -0,0 +1,17 @@
F no_args() {}
// call
no_args()
F fixed_args(x, y)
print(x=#., y=#..format(x, y))
// call
fixed_args(1, 2) // x=1, y=2
// named arguments
fixed_args(x' 1, y' 2)
F opt_args(x = 1)
print(x)
// calls
opt_args() // 1
opt_args(3.141) // 3.141

View file

@ -0,0 +1,3 @@
X DS F
Y DS F
Z DS F

View file

@ -0,0 +1,7 @@
L R15,=V(MULTPLIC)
LA R1,PARMLIST address of the paramter list
BALR R14,R15 branch and link
ST R0,Z Z=MULTPLIC(X,Y)
* ...
PARMLIST DC A(X)
DC A(Y)

View file

@ -0,0 +1,2 @@
CALL MULTPLIC,(X,Y) call MULTPLIC(X,Y)
ST R0,Z Z=MULTPLIC(X,Y)

View file

@ -0,0 +1,4 @@
LOAD EP=MULTPLIC load load-module
LR R15,R0 retrieve entry address
CALL (R15),(X,Y) call MULTPLIC(X,Y)
ST R0,Z Z=MULTPLIC(X,Y)

View file

@ -0,0 +1 @@
JSR myFunction

View file

@ -0,0 +1,6 @@
sum:
;adds the values in zero page address $00 and $01, outputs to accumulator.
LDA $00 ;load the byte stored at memory address $0000
CLC
ADC $01 ;add the byte at memory address $0001
RTS ;return

View file

@ -0,0 +1 @@
JSR myFunction

View file

@ -0,0 +1 @@
call foo

View file

@ -0,0 +1,10 @@
push ax ;second argument
push bx ;first argument - typically arguments are pushed in the reverse order they are listed.
call foo
pop bx
pop ax
foo:
push bp
mov bp,sp
;now bp+4 = the value pushed from BX, and bp+6 = the value pushed from AX

View file

@ -0,0 +1,2 @@
foo:
ld ax,word ptr[ds:bar] ;load from bar, which is a 16 bit storage location in the data segment (DS), into AX

View file

@ -0,0 +1,3 @@
mov AH,4Ch
mov AL,00h
int 21h

View file

@ -0,0 +1,99 @@
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program callfonct.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/***********************/
/* Initialized data */
/***********************/
.data
szMessage: .asciz "Hello. \n" // message
szRetourLigne: .asciz "\n"
szMessResult: .asciz "Resultat : " // message result
/***********************/
/* No Initialized data */
/***********************/
.bss
sZoneConv: .skip 100
.text
.global main
main:
ldr x0,=szMessage // adresse of message short program
bl affichageMess // call function with 1 parameter (x0)
// call function with parameters in register
mov x0,#5
mov x1,#10
bl fonction1 // call function with 2 parameters (x0,x1)
ldr x1,qAdrsZoneConv // result in x0
bl conversion10S // call function with 2 parameter (x0,x1)
ldr x0,=szMessResult
bl affichageMess // call function with 1 parameter (x0)
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
// call function with parameters on stack
mov x0,#5
mov x1,#10
stp x0,x1,[sp,-16]! // store registers on stack
bl fonction2 // call function with 2 parameters on the stack
// result in x0
ldr x1,qAdrsZoneConv
bl conversion10S // call function with 2 parameter (x0,x1)
ldr x0,=szMessResult
bl affichageMess // call function with 1 parameter (x0)
ldr x0,qAdrsZoneConv
bl affichageMess
ldr x0,qAdrszRetourLigne
bl affichageMess
// end of program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszRetourLigne: .quad szRetourLigne
/******************************************************************/
/* call function parameter in register */
/******************************************************************/
/* x0 value one */
/* x1 value two */
/* return in x0 */
fonction1:
stp x2,lr,[sp,-16]! // save registers
mov x2,#20
mul x0,x0,x2
add x0,x0,x1
ldp x2,lr,[sp],16 // restaur 2 registres
ret // retour adresse lr x30
/******************************************************************/
/* call function parameter in the stack */
/******************************************************************/
/* return in x0 */
fonction2:
stp fp,lr,[sp,-16]! // save registers
add fp,sp,#16 // address parameters in the stack
stp x1,x2,[sp,-16]! // save others registers
ldr x0,[fp] // second paraméter
ldr x1,[fp,#8] // first parameter
mov x2,#-20
mul x0,x0,x2
add x0,x0,x1
ldp x1,x2,[sp],16 // restaur 2 registres
ldp fp,lr,[sp],16 // restaur 2 registres
add sp,sp,#16 // very important, for stack aligned
ret // retour adresse lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

View file

@ -0,0 +1,39 @@
# Note functions and subroutines are called procedures (or PROCs) in Algol 68 #
# A function called without arguments: #
f;
# Algol 68 does not expect an empty parameter list for calls with no arguments, "f()" is a syntax error #
# A function with a fixed number of arguments: #
f(1, x);
# variable number of arguments: #
# functions that accept an array as a parameter can effectively provide variable numbers of arguments #
# a "literal array" (called a row-display in Algol 68) can be passed, as is often the case for the I/O #
# functions - e.g.: #
print( ( "the result is: ", r, " after ", n, " iterations", newline ) );
# the outer brackets indicate the parameters of print, the inner brackets indicates the contents are a "literal array" #
# ALGOL 68 does not support optional arguments, though in some cases an empty array could be passed to a function #
# expecting an array, e.g.: #
f( () );
# named arguments - see the Algol 68 sample in: http://rosettacode.org/wiki/Named_parameters #
# In "Talk:Call a function" a statement context is explained as
"The function is used as an instruction (with a void context),
rather than used within an expression."
Based on that, the examples above are already in a statement context.
Technically, when a function that returns other than VOID (i.e. is not a subroutine)
is called in a statement context, the result of the call is "voided" i.e. discarded.
If desired, this can be made explicit using a cast, e.g.: #
VOID(f);
# A function's return value being used: #
x := f(y);
# There is no distinction between built-in functions and user-defined functions. #
# A subroutine is simply a function that returns VOID. #
# If the function is declared with argument(s) of mode REF MODE,
then those arguments are being passed by reference. #
# Technically, all parameters are passed by value, however the value of a REF MODE is a reference... #

View file

@ -0,0 +1,38 @@
% Note, in Algol W, functions are called procedures %
% calling a function with no parameters: %
f;
% calling a function with a fixed number of parameters %
g( 1, 2.3, "4" );
% Algol W does not support optional parameters in general, however constructors for records can %
% be called wither with parameters (one for each field in the record) or no parameters #
% Algol W does not support variable numbers of parameters, except for the built-in I/O functions #
% Algol W does not support named arguments %
% A function can be used in a statement context by calling it, as in the examples above %
% First class context: A function can be passed as a parameter to another procedure, e.g.: %
v := integrate( sin, 0, 1 )
% assuming a suitable definition of integrate %
% Algol W does not support functions returning functions %
% obtaining the return value of a function: e.g.: %
v := g( x, y, z );
% There is no syntactic distinction between user-defined and built-in functions %
% Subroutines and functions are both procedures, a subroutine is a procedure with no return type %
% (called a proper procedure in Algol W) %
% There is no syntactic distinction between a call to a function and a call to a subroutine %
% other than the context %
% In Algol W, parameters are passed by value, result or value result. This must be stated in the %
% definition of the function/subroutine. Value parameters are passed by value, result and value result %
% are effectively passed by reference and assigned on function exit. Result parameters are "out" parameters %
% and value result parameters are "in out". %
% Algol W also has "name" parameters (not to be confused with named parameters). Functions with name %
% parameters are somewhat like macros %
% Partial application is not possible in Algol W %

View file

@ -0,0 +1 @@
2*2+9

View file

@ -0,0 +1,3 @@
*[2;+[2;9]]
echo["Hello!"]
time[]

View file

@ -0,0 +1,171 @@
/* ARM assembly Raspberry PI */
/* program callfonct.s */
/* Constantes */
.equ STDOUT, 1
.equ WRITE, 4
.equ EXIT, 1
/***********************/
/* Initialized data */
/***********************/
.data
szMessage: .asciz "Hello. \n" @ message
szRetourLigne: .asciz "\n"
szMessResult: .ascii "Resultat : " @ message result
sMessValeur: .fill 12, 1, ' '
.asciz "\n"
/***********************/
/* No Initialized data */
/***********************/
.bss
iValeur: .skip 4 @ reserve 4 bytes in memory
.text
.global main
main:
ldr r0,=szMessage @ adresse of message short program
bl affichageMess @ call function with 1 parameter (r0)
@ call function with parameters in register
mov r0,#5
mov r1,#10
bl fonction1 @ call function with 2 parameters (r0,r1)
ldr r1,=sMessValeur @ result in r0
bl conversion10S @ call function with 2 parameter (r0,r1)
ldr r0,=szMessResult
bl affichageMess @ call function with 1 parameter (r0)
@ call function with parameters on stack
mov r0,#5
mov r1,#10
push {r0,r1}
bl fonction2 @ call function with 2 parameters on the stack
@ result in r0
ldr r1,=sMessValeur
bl conversion10S @ call function with 2 parameter (r0,r1)
ldr r0,=szMessResult
bl affichageMess @ call function with 1 parameter (r0)
/* end of program */
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
/******************************************************************/
/* call function parameter in register */
/******************************************************************/
/* r0 value one */
/* r1 value two */
/* return in r0 */
fonction1:
push {fp,lr} /* save des 2 registres */
push {r1,r2} /* save des autres registres */
mov r2,#20
mul r0,r2
add r0,r0,r1
pop {r1,r2} /* restaur des autres registres */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* retour procedure */
/******************************************************************/
/* call function parameter in the stack */
/******************************************************************/
/* return in r0 */
fonction2:
push {fp,lr} /* save des 2 registres */
add fp,sp,#8 /* address parameters in the stack*/
push {r1,r2} /* save des autres registres */
ldr r0,[fp]
ldr r1,[fp,#4]
mov r2,#-20
mul r0,r2
add r0,r0,r1
pop {r1,r2} /* restaur des autres registres */
pop {fp,lr} /* restaur des 2 registres */
add sp,#8 /* very important, for stack aligned */
bx lr /* retour procedure */
/******************************************************************/
/* affichage des messages avec calcul longueur */
/******************************************************************/
/* r0 contient l adresse du message */
affichageMess:
push {fp,lr} /* save des 2 registres */
push {r0,r1,r2,r7} /* save des autres registres */
mov r2,#0 /* compteur longueur */
1: /*calcul de la longueur */
ldrb r1,[r0,r2] /* recup octet position debut + indice */
cmp r1,#0 /* si 0 c est fini */
beq 1f
add r2,r2,#1 /* sinon on ajoute 1 */
b 1b
1: /* donc ici r2 contient la longueur du message */
mov r1,r0 /* adresse du message en r1 */
mov r0,#STDOUT /* code pour écrire sur la sortie standard Linux */
mov r7, #WRITE /* code de l appel systeme 'write' */
swi #0 /* appel systeme */
pop {r0,r1,r2,r7} /* restaur des autres registres */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* retour procedure */
/***************************************************/
/* conversion registre en décimal signé */
/***************************************************/
/* r0 contient le registre */
/* r1 contient l adresse de la zone de conversion */
conversion10S:
push {fp,lr} /* save des 2 registres frame et retour */
push {r0-r5} /* save autres registres */
mov r2,r1 /* debut zone stockage */
mov r5,#'+' /* par defaut le signe est + */
cmp r0,#0 /* nombre négatif ? */
movlt r5,#'-' /* oui le signe est - */
mvnlt r0,r0 /* et inversion en valeur positive */
addlt r0,#1
mov r4,#10 /* longueur de la zone */
1: /* debut de boucle de conversion */
bl divisionpar10 /* division */
add r1,#48 /* ajout de 48 au reste pour conversion ascii */
strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */
sub r4,r4,#1 /* position précedente */
cmp r0,#0
bne 1b /* boucle si quotient different de zéro */
strb r5,[r2,r4] /* stockage du signe à la position courante */
subs r4,r4,#1 /* position précedente */
blt 100f /* si r4 < 0 fin */
/* sinon il faut completer le debut de la zone avec des blancs */
mov r3,#' ' /* caractere espace */
2:
strb r3,[r2,r4] /* stockage du byte */
subs r4,r4,#1 /* position précedente */
bge 2b /* boucle si r4 plus grand ou egal a zero */
100: /* fin standard de la fonction */
pop {r0-r5} /*restaur des autres registres */
pop {fp,lr} /* restaur des 2 registres frame et retour */
bx lr
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 contient le dividende */
/* r0 retourne le quotient */
/* r1 retourne le reste */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save autres registres */
mov r4,r0
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
.align 4
.Ls_magic_number_10: .word 0x66666667

View file

@ -0,0 +1,4 @@
BEGIN {
sayhello() # Call a function with no parameters in statement context
b=squareit(3) # Obtain the return value from a function with a single parameter in first class context
}

View file

@ -0,0 +1,3 @@
myfunction(); /* function with no arguments in statement context */
myfunction(6,b); // function with two arguments in statement context
stringit("apples"); //function with a string argument

View file

@ -0,0 +1 @@
S: String := Ada.Text_IO.Get_Line;

View file

@ -0,0 +1,5 @@
function F(X: Integer; Y: Integer := 0) return Integer; -- Y is optional
...
A : Integer := F(12);
B : Integer := F(12, 0); -- the same as A
C : Integer := F(12, 1); -- something different

View file

@ -0,0 +1,12 @@
type Integer_Array is array (Positive range <>) of Integer;
function Sum(A: Integer_Array) return Integer is
S: Integer := 0;
begin
for I in A'Range loop
S := S + A(I);
end loop;
return S;
end Sum;
...
A := Sum((1,2,3)); -- A = 6
B := Sum((1,2,3,4)); -- B = 10

View file

@ -0,0 +1,9 @@
function H (Int: Integer;
Fun: not null access function (X: Integer; Y: Integer)
return Integer);
return Integer;
...
X := H(A, F'Access) -- assuming X and A are Integers, and F is a function
-- taking two Integers and returning an Integer.

View file

@ -0,0 +1,3 @@
Positional := H(A, F'Access);
Named := H(Int => A, Fun => F'Access);
Mixed := H(A, Fun=>F'Access);

View file

@ -0,0 +1,36 @@
printHello: $[][
print "Hello World!"
]
sayHello: $[name][
print ["Hello" name "!"]
]
printAll: $[args][
loop args [arg][
print arg
]
]
getNumber: $[][3]
; Calling a function that requires no arguments
printHello
; Calling a function with a fixed number of arguments
sayHello "John"
; Calling a function with a variable number of arguments
printAll ["one" "two" "three"]
; Using a function in statement context
if true [printHello]
print getNumber
; Using a function in first-class context within an expression
if getNumber=3 [print "yep, it worked"]
; Obtaining the return value of a function:
num: getNumber
print num

View file

@ -0,0 +1,39 @@
; Call a function without arguments:
f()
; Call a function with a fixed number of arguments:
f("string", var, 15.5)
; Call a function with optional arguments:
f("string", var, 15.5)
; Call a function with a variable number of arguments:
f("string", var, 15.5)
; Call a function with named arguments:
; AutoHotkey does not have named arguments. However, in v1.1+,
; we can pass an object to the function:
f({named: "string", otherName: var, thirdName: 15.5})
; Use a function in statement context:
f(1), f(2) ; What is statement context?
; No first-class functions in AHK
; Obtaining the return value of a function:
varThatGetsReturnValue := f(1, "a")
; Cannot distinguish built-in functions
; Subroutines are called with GoSub; functions are called as above.
; Subroutines cannot be passed variables
; Stating whether arguments are passed by value or by reference:
; [v1.1.01+]: The IsByRef() function can be used to determine
; whether the caller supplied a variable for a given ByRef parameter.
; A variable cannot be passed by value to a byRef parameter. Instead, do this:
f(tmp := varIdoNotWantChanged)
; the function f will receive the value of varIdoNotWantChanged, but any
; modifications will be made to the variable tmp.
; Partial application is impossible.

View file

@ -0,0 +1,2 @@
NOARG()
ARGS(1,5,42)

View file

@ -0,0 +1,3 @@
OPARG(1,2,3,4,5,6)
OPARG(1,2,3)
OPARG()

View file

@ -0,0 +1,2 @@
MATHS(2,4)→A
Disp GETSTR()

View file

@ -0,0 +1,2 @@
USER()
axeFunc()

View file

@ -0,0 +1,33 @@
function Copialo$ (txt$, siNo, final$)
nuevaCadena$ = ""
for cont = 1 to siNo
nuevaCadena$ += txt$
next cont
return trim(nuevaCadena$) + final$
end function
subroutine Saludo()
print "Hola mundo!"
end subroutine
subroutine testCadenas (txt$)
for cont = 1 to length(txt$)
print mid(txt$, cont, 1); "";
next cont
end subroutine
subroutine testNumeros (a, b, c)
print a, b, c
end subroutine
call Saludo()
print Copialo$("Saludos ", 6, "")
print Copialo$("Saludos ", 3, "!!")
print
call testNumeros(1, 2, 3)
call testNumeros(1, 2, 0)
print
call testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \#incluye texto\#")
end

View file

@ -0,0 +1 @@
PRINT SQR(2)

View file

@ -0,0 +1 @@
PRINT SQR 2

View file

@ -0,0 +1 @@
PRINT FN_foo(bar$, baz%)

View file

@ -0,0 +1 @@
PRINT FN_foo

View file

@ -0,0 +1 @@
PROC_foo

View file

@ -0,0 +1 @@
PROC_foo(bar$, baz%, quux)

View file

@ -0,0 +1 @@
DEF PROC_foo(a$, RETURN b%, RETURN c)

View file

@ -0,0 +1 @@
200 GOSUB 30050

View file

@ -0,0 +1 @@
{𝕊 ·: 1 + 1}0

View file

@ -0,0 +1 @@
2-

View file

@ -0,0 +1 @@
F 1

View file

@ -0,0 +1 @@
2 F 1

View file

@ -0,0 +1,4 @@
{
𝕊 onetwothree:
onetwothree
}

View file

@ -0,0 +1 @@
1 {𝕨+𝕩} 2

View file

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

View file

@ -0,0 +1 @@
+, -,

View file

@ -0,0 +1 @@
var Func # insert arg here

View file

@ -0,0 +1 @@
+2

View file

@ -0,0 +1,86 @@
:: http://rosettacode.org/wiki/Call_a_function
:: Demonstrate the different syntax and semantics provided for calling a function.
@echo off
echo Calling myFunction1
call:myFunction1
echo.
echo Calling myFunction2 11 8
call:myFunction2 11 8
echo.
echo Calling myFunction3 /fi and saving the output into %%filecount%%
call:myFunction3 /fi
echo.%filecount%
echo.
echo Calling myFunction4 1 2 3 4 5
call:myFunction4 1 2 3 4 5
echo.
echo Calling myFunction5 "filename=test.file" "filepath=C:\Test Directory\"
call:myFunction5 "filename=test.file" "filepath=C:\Test Directory\"
echo.
echo Calling myFunction5 "filepath=C:\Test Directory\" "filename=test.file"
call:myFunction5 "filepath=C:\Test Directory\" "filename=test.file"
echo.
pause>nul
exit
:: Requires no arguments
:myFunction1
echo myFunction1 has been called.
goto:eof
:: Fixed number of arguments (%a% & %b%)
:myFunction2
:: Returns %a% + %b%
setlocal
set /a c=%~1+%~2
endlocal & echo %c%
goto:eof
:: Optional arguments
:myFunction3
:: Returns the amount of folders + files in the current directory
:: /fi Returns only file count
:: /fo Returns only folder count
setlocal
set count=0
if "%~1"=="" set "command=dir /b"
if "%~1"=="/fi" set "command=dir /b /A-d"
if "%~1"=="/fo" set "command=dir /b /Ad"
for /f "usebackq" %%i in (`%command%`) do set /a count+=1
endlocal & set filecount=%count%
goto:eof
:: Variable number of arguments
:myFunction4
:: Returns sum of arguments
setlocal
:myFunction4loop
set sum=0
for %%i in (%*) do set /a sum+=%%i
endlocal & echo %sum%
goto:eof
:: Named Arguments (filepath=[path] & filename=[name])
:myFunction5
:: Returns the complete path based off the 2 arguments
if "%~1"=="" then goto:eof
setlocal enabledelayedexpansion
set "param=%~1"
for /l %%i in (1,1,2) do (
for /f "tokens=1,2 delims==" %%j in ("!param!") do set %%j=%%k
set "param=%~2"
)
endlocal & echo.%filepath%%filename%
goto:eof

View file

@ -0,0 +1 @@
aFunctionWithoutArguments$

View file

@ -0,0 +1 @@
aFunctionWithoutArguments'

View file

@ -0,0 +1 @@
func$!myargument;

View file

@ -0,0 +1 @@
(yourfunc=local vars.function body)

View file

@ -0,0 +1 @@
('$myfunc:(=?yourfunc))

View file

@ -0,0 +1 @@
myfunc$!myarg:?myresult

View file

@ -0,0 +1 @@
myfunc$!myarg&yourfunc$!yourarg

View file

@ -0,0 +1 @@
`(myfunc$!myarg)&yourfunc$!yourarg

View file

@ -0,0 +1,10 @@
( ( plus
= a b
. !arg:%?a ?b
& !b:
& '(.!arg+$a)
| !a+!b
)
& out$("1+2, not partial:" plus$(1 2))
& out$("1+2, partial:" (plus$1)$2)
);

View file

@ -0,0 +1,2 @@
/* function with no arguments */
foo();

View file

@ -0,0 +1,5 @@
/* passing arguments by value*/
/* function with one argument */
bar(arg1);
/* function with multiple arguments */
baz(arg1, arg2);

View file

@ -0,0 +1,2 @@
/* get return value of a function */
variable = function(args);

View file

@ -0,0 +1,14 @@
#include <iostream>
using namespace std;
/* passing arguments by reference */
void f(int &y) /* variable is now passed by reference */
{
y++;
}
int main()
{
int x = 0;
cout<<"x = "<<x<<endl; /* should produce result "x = 0" */
f(x); /* call function f */
cout<<"x = "<<x<<endl; /* should produce result "x = 1" */
}

View file

@ -0,0 +1,30 @@
/* a function that has no argument */
public int MyFunction();
/* a function with a fixed number of arguments */
FunctionWithArguments(4, 3, 2);
/* a function with optional arguments */
public void OptArg();
public static void Main()
{
OptArg(1);
OptArg(1, 2);
OptArg(1, 2, 3);
}
public void ExampleMethod(int required,
string optionalstr = "default string",
int optionalint = 10)
/* If you know the first and the last parameter */
ExampleMethod(3, optionalint: 4);
/* If you know all the parameter */
ExampleMethod(3, "Hello World", 4);
/* Variable number of arguments use array */
public static void UseVariableParameters(params int[] list)
/* Obtain return value from function */
public internal MyFunction();
int returnValue = MyFunction();

View file

@ -0,0 +1,65 @@
/* function with no argument */
f();
/* fix number of arguments */
g(1, 2, 3);
/* Optional arguments: err...
Feel free to make sense of the following. I can't. */
int op_arg();
int main()
{
op_arg(1);
op_arg(1, 2);
op_arg(1, 2, 3);
return 0;
}
int op_arg(int a, int b)
{
printf("%d %d %d\n", a, b, (&b)[1]);
return a;
} /* end of sensible code */
/* Variadic function: how the args list is handled solely depends on the function */
void h(int a, ...)
{
va_list ap;
va_start(ap);
...
}
/* call it as: (if you feed it something it doesn't expect, don't count on it working) */
h(1, 2, 3, 4, "abcd", (void*)0);
/* named arguments: this is only possible through some pre-processor abuse
*/
struct v_args {
int arg1;
int arg2;
char _sentinel;
};
void _v(struct v_args args)
{
printf("%d, %d\n", args.arg1, args.arg2);
}
#define v(...) _v((struct v_args){__VA_ARGS__})
v(.arg2 = 5, .arg1 = 17); // prints "17,5"
/* NOTE the above implementation gives us optional typesafe optional arguments as well (unspecified arguments are initialized to zero)*/
v(.arg2=1); // prints "0,1"
v(); // prints "0,0"
/* as a first-class object (i.e. function pointer) */
printf("%p", f); /* that's the f() above */
/* return value */
double a = asin(1);
/* built-in functions: no such thing. Compiler may interally give special treatment
to bread-and-butter functions such as memcpy(), but that's not a C built-in per se */
/* subroutines: no such thing. You can goto places, but I doubt that counts. */
/* Scalar values are passed by value by default. However, arrays are passed by reference. */
/* Pointers *sort of* work like references, though. */

View file

@ -0,0 +1,65 @@
CALL "No-Arguments"
*> Fixed number of arguments.
CALL "2-Arguments" USING Foo Bar
CALL "Optional-Arguments" USING Foo
CALL "Optional-Arguments" USING Foo Bar
*> If an optional argument is omitted and replaced with OMITTED, any following
*> arguments can still be specified.
CALL "Optional-Arguments" USING Foo OMITTED Bar
*> Interestingly, even arguments not marked as optional can be omitted without
*> a compiler warning. It is highly unlikely the function will still work,
*> however.
CALL "2-Arguments" USING Foo
*> COBOL does not support a variable number of arguments, or named arguments.
*> Values to return can be put in either one of the arguments or, in OpenCOBOL,
*> the RETURN-CODE register.
*> A standard function call cannot be done in another statement.
CALL "Some-Func" USING Foo
MOVE Return-Code TO Bar
*> Intrinsic functions can be used in any place a literal value may go (i.e. in
*> statements) and are optionally preceded by FUNCTION.
*> Intrinsic functions that do not take arguments may optionally have a pair of
*> empty parentheses.
*> Intrinsic functions cannot be defined by the user.
MOVE FUNCTION PI TO Bar
MOVE FUNCTION MEDIAN(4, 5, 6) TO Bar
*> Built-in functions/subroutines typically have prefixes indicating which
*> compiler originally incorporated it:
*> - C$ - ACUCOBOL-GT
*> - CBL_ - Micro Focus
*> - CBL_OC_ - OpenCOBOL
*> Note: The user could name their functions similarly if they wanted to.
CALL "C$MAKEDIR" USING Foo
CALL "CBL_CREATE_DIR" USING Foo
CALL "CBL_OC_NANOSLEEP" USING Bar
*> Although some built-in functions identified by numbers.
CALL X"F4" USING Foo Bar
*> Parameters can be passed in 3 different ways:
*> - BY REFERENCE - this is the default way in OpenCOBOL and this clause may
*> be omitted. The address of the argument is passed to the function.
*> The function is allowed to modify the variable.
*> - BY CONTENT - a copy is made and the function is passed the address
*> of the copy, which it can then modify. This is recomended when
*> passing a literal to a function.
*> - BY VALUE - the function is passed the address of the argument (like a
*> pointer). This is mostly used to provide compatibility with other
*> languages, such as C.
CALL "Modify-Arg" USING BY REFERENCE Foo *> Foo is modified.
CALL "Modify-Arg" USING BY CONTENT Foo *> Foo is unchanged.
CALL "C-Func" USING BY VALUE Bar
*> Partial application is impossible as COBOL does not support first-class
*> functions.
*> However, as functions are called using a string of their PROGRAM-ID,
*> you could pass a 'function' as an argument to another function, or store
*> it in a variable, or get it at runtime.
ACCEPT Foo *> Get a PROGRAM-ID from the user.
CALL "Use-Func" USING Foo
CALL Foo USING Bar

View file

@ -0,0 +1,5 @@
(defn one []
"Function that takes no arguments and returns 1"
1)
(one); => 1

View file

@ -0,0 +1,15 @@
;;You can assign it to a variable:
(def receipt-us (format-receipt "Toilet Paper" 5 format-price-us))
;; Then the variable holds the value
receipt-us; => "Toilet Paper $5"
;; Or you can use it in a call to another function
(defn add-store-name [receipt]
"A function to add a footer to the receipt"
(str receipt "\n Thanks for shopping at Safeway" ))
;; Calls add-store-name with the result of the format function
(add-store-name (format-receipt "Toilet Paper" 5 format-price-us)); => "Toilet Paper $5\n Thanks for shopping at Safeway"

View file

@ -0,0 +1,21 @@
;; They are indistinguishable in Clojure, and you can even override a built in one
;; Using built-in addition
(+ 5 5); => 10
;; Using custom defined addition
(defn ? [a b]
"Returns the sum of two numbers"
(+ a b))
(? 5 5); => 10
;; Overriding a built in function is possible but not recommended
(defn * [a b] ;; Redefining the multiplication operator
"Returns the sum of two numbers"
(+ a b))
(* 5 5); => 10

View file

@ -0,0 +1,7 @@
;; They are the same thing - indeed, everything in clojure is a function
;; Functions without return values simply return nil
(defn no-return-value [a]
(print (str "Your argument was" a "; now returning nil")))
(no-return-value "hi"); => nil

View file

@ -0,0 +1,18 @@
;; Set up a variable that we will pass to a function
(def the-queen {:name "Elizabeth"
:title "Your Majesty"
:address "Buckingham Palace"
:pets ["Corgi" "Horse"]})
;; A function to modify the data
(defn adopt-pet [person pet]
"Adds pet to the person's list of pets"
(update person
:pets
#(conj % pet)))
;; Calling the function returns a new data structure with the modified pets
(adopt-pet the-queen "Ferret"); => {:name "Elizabeth":title "Your Majesty" :address "Buckingham Palace" :pets ["Corgi" "Horse" "Ferret]}
;; The original data structure is not changed
the-queen; => {:name "Elizabeth" :title "Your Majesty" :address "Buckingham Palace" :pets ["Corgi" "Horse"]}

View file

@ -0,0 +1,17 @@
(defn apply-discount [discount-percentage price]
"Function to apply a discount to a price"
(-> price
(* (- 100 discount-percentage)) ;; Apply discount
(/ 100.0)))
;; Here we have assigned the variable to a partial function
;; It means 'call apply-discount with 10 as the first argument'
(def discount-10pc-option-1 (partial apply-discount 10))
;; And is equivalent to this:
(defn discount-10pc-option-2 [price]
(apply-discount 10 price))
(discount-10pc-option-1 100); => 90
(discount-10pc-option-2 100); => 90

View file

@ -0,0 +1,5 @@
(defn total-cost [item-price num-items]
"Returns the total price to buy the given number of items"
(* item-price num-items))
(total-cost 1 5); => 5

View file

@ -0,0 +1,13 @@
(defn total-cost-with-discount [item-price num-items & [discount-percentage]]
"Returns total price to buy the items after discount is applied (if given)"
(let [discount (or discount-percentage 0)] ;; Assign discount to either the discount-percentage (if given) or default 0 if not
(-> item-price
(* num-items) ;; Calculate total cost
(* (- 100 discount)) ;; Apply discount
(/ 100.0))))
;; Now we can use the function without the optional arguments, and see the same behaviour as our total-cost function
(total-cost-with-discount 1 5); => 5
;; Or we can add the third parameter to calculate the cost with 20% discount
(total-cost-with-discount 1 5 20); => 4

View file

@ -0,0 +1,15 @@
(defn make-address
([city place-name] (str place-name ", " city))
([city street house-number] (str house-number " " street ", " city))
([city street house-number apartment] (str house-number " " street ", Apt. " apartment ", " city)))
;; To call the function you just need to pass whatever arguments you are supplying as you would with a fixed number
;; First case- the queen doesn't need a street name
(make-address "London" "Buckingham Palace"); => "Buckingham Palace, London"
;; Second case
(make-address "London" "Downing Street" 10); => "10 Downing Street, London"
;; Third case
(make-address "London" "Baker Street" 221 "B"); => "221 Baker Street, Apt. B, London"

View file

@ -0,0 +1,12 @@
(defn make-mailing-label [{:keys [name address country]}]
"Returns the correct text to mail a letter to the addressee"
(str name "\n" address "\n" (or country "UK"))) ;; If country is nil, assume it is the UK
;; We can call it with all three arguments in a map to get mickey's international address
(make-mailing-label {:name "Mickey Mouse"
:address "1 Disney Avenue, Los Angeles"
:country "USA"}); => "Mickey Mouse\n1 Disney Avenue, Los Angeles\nUSA"
;; Or we can call it with fewer arguments for domestic mail
(make-mailing-label {:name "Her Majesty"
:address "Buckingham Palace, London"}); => "Her Majesty\nBuckingham Palace, London\nUK"

View file

@ -0,0 +1,6 @@
(defn multiply-by-10 [number]
(* 10 number))
(def fifty (multiply-by-10 5))
fifty; => 50

View file

@ -0,0 +1,17 @@
(defn make-discount-function [discount-percent]
"Returns a function that takes a price and applies the given discount"
(fn [price] (-> price
(* (- 100 discount-percent))
(/ 100.0))))
;; Now we can create a '20% off' function to calculate prices with your discount card
(def discount-20pc (make-discount-function 20))
;; Use the function to calculate some discount prices
(discount-20pc 100); => 80
(discount-20pc 5); => 4
;; Your friend has a better discount card, we can use the same function to create their discount card function
(def discount-50pc (make-discount-function 50))
(discount-50pc 100); => 50
(discount-50pc 5); => 2.5

View file

@ -0,0 +1,16 @@
;; Continuing on the same example, let's imagine Anna has a 20% discount card and Bill has 50%. Charlie pays full price
;; We can store their discount functions in a map
(def discount-cards {"Anna" discount-20pc
"Bill" discount-50pc
"Charlie" identity}) ;; Identity returns whatever value was passed to the function (in this case it will be price)
;; Now we can access them by cardholder name in another function
(defn calculate-discounted-price [price shopper-name]
"Applies the correct discount for the person"
(let [discount-fn (get discount-cards shopper-name)] ;; Get the right discount function
(discount-fn price))) ;; Apply discount function to the price
(calculate-discounted-price 100 "Anna"); => 80
(calculate-discounted-price 100 "Bill"); => 50
(calculate-discounted-price 100 "Charlie"); => 100

View file

@ -0,0 +1,19 @@
;; Here we have two functions to format a price depending on the country
(defn format-price-uk [price]
(str "£" price))
(defn format-price-us [price]
(str "$" price))
;; And one function that takes a price formatting function as an argument
(defn format-receipt [item-name price price-formatting-function]
"Return the item name and price formatted according to the function"
(str item-name
" "
(price-formatting-function price))) ;; Call the format function to get the right representation of the price
(format-receipt "Loo Roll" 5 format-price-uk); => "Loo Roll £5"
(format-receipt "Toilet Paper" 5 format-price-us); => "Toilet Paper $5"

View file

@ -0,0 +1,52 @@
# Calling a function that requires no arguments
foo()
# Calling a function with a fixed number of arguments
foo 1
# Calling a function with optional arguments
# (Optional arguments are done using an object with named keys)
foo 1, optionalBar: 1, optionalBaz: 'bax'
# Calling a function with a variable number of arguments
# for a function `foo` defined as `foo = ( args... ) ->`
foo 1, 2, 3, 4
# Calling a function with named arguments
# (Named arguments are done using an object with named keys)
foo bar: 1, bax: 'baz'
# Using a function in statement context
x = foo 1
# Using a function in first-class context within an expression
# (For `foo` defined as `foo = ( x ) -> x + 1`
x = [ 1, 2, 3 ].map foo
# Obtaining the return value of a function
x = foo 1
# Arguments are passed by value, even objects. Objects
# are passed as the _value_ of the reference to an object.
# Example:
bar = ( person ) ->
# Since `person` is a reference
# to the person passed in, we can assign
# a new value to its `name` key.
person.name = 'Bob'
# Since `person` is just the value of
# the original reference, assigning to it
# does not modify the original reference.
person = new Person 'Frank'
# Partial application is only possible manually through closures
curry = ( f, fixedArgs... ) ->
( args... ) -> f fixedArgs..., args...
# Example usage
add = ( x, y ) -> x + y
add2 = curry add, 2
add2 1 #=> 3

View file

@ -0,0 +1,25 @@
;Calling a function that requires no arguments
(defun a () "This is the 'A' function")
(a)
;Calling a function with a fixed number of arguments
(defun b (x y) (list x y))
(b 1 2)
;Calling a function with optional arguments
(defun c (&optional x y) (list x y))
(c 1)
;Calling a function with a variable number of arguments
(defun d (&rest args) args)
(d 1 2 3 4 5 6 7 8)
;Calling a function with named arguments
(defun e (&key (x 1) (y 2)) (list x y))
(e :x 10 :y 20)
;Using a function in first-class context within an expression
(defun f (func) (funcall func))
(f #'a)
;Obtaining the return value of a function
(defvar return-of-a (a))
;Is partial application possible and how
(defun curry (function &rest args-1)
(lambda (&rest args-2)
(apply function (append args-1 args-2))))
(funcall (curry #'+ 1) 2)

View file

@ -0,0 +1,16 @@
// No arguments
myfunction
// All functions can take a variable number of arguments.
// These can be accessed from within the function with the aliases:
// $arg1, $arg2, $arg3... $numargs tells the amount of args passed.
myfunction word "text string" 1 3.14
// Getting a function's return value
retval = (myfunction)
// Trying to do a variable lookup on a builtin function will return an empty
// string. This can be used to distinguish builtin functions from user-defined
// ones.
if (strcmp $echo "") [echo builtin function] // true
if (strcmp $myfunction "") [echo builtin function] // false

View file

@ -0,0 +1,103 @@
import std.traits;
enum isSubroutine(alias F) = is(ReturnType!F == void);
void main() {
void foo1() {}
// Calling a function that requires no arguments:
foo1();
foo1; // Alternative syntax.
void foo2(int x, int y) {}
immutable lambda = function int(int x) => x ^^ 2;
// Calling a function with a fixed number of arguments:
foo2(1, 2);
foo2(1, 2);
cast(void)lambda(1);
void foo3(int x, int y=2) {}
// Calling a function with optional arguments:
foo3(1);
foo3(1, 3);
int sum(int[] arr...) {
int tot = 0;
foreach (immutable x; arr)
tot += x;
return tot;
}
real sum2(Args...)(Args arr) {
typeof(return) tot = 0;
foreach (immutable x; arr)
tot += x;
return tot;
}
// Calling a function with a variable number of arguments:
assert(sum(1, 2, 3) == 6);
assert(sum(1, 2, 3, 4) == 10);
assert(sum2(1, 2.5, 3.5) == 7);
// Calling a function with named arguments:
// Various struct or tuple-based tricks can be used for this,
// but currently D doesn't have named arguments.
// Using a function in statement context (?):
if (1)
foo1;
// Using a function in first-class context within an expression:
assert(sum(1) == 1);
auto foo4() { return 1; }
// Obtaining the return value of a function:
immutable x = foo4;
// Distinguishing built-in functions and user-defined functions:
// There are no built-in functions, beside the operators, and
// pseudo-functions like assert().
int myFynction(int x) { return x; }
void mySubroutine(int x) {}
// Distinguishing subroutines and functions:
// (A subroutine is merely a function that has no explicit
// return statement and will return void).
pragma(msg, isSubroutine!mySubroutine); // Prints: true
pragma(msg, isSubroutine!myFynction); // Prints: false
void foo5(int a, in int b, ref int c, out int d, lazy int e, scope int f) {}
// Stating whether arguments are passed by value, by reference, etc:
alias STC = ParameterStorageClass;
alias psct = ParameterStorageClassTuple!foo5;
static assert(psct.length == 6); // Six parameters.
static assert(psct[0] == STC.none);
static assert(psct[1] == STC.none);
static assert(psct[2] == STC.ref_);
static assert(psct[3] == STC.out_);
static assert(psct[4] == STC.lazy_);
static assert(psct[5] == STC.scope_);
// There are also inout and auto ref.
int foo6(int a, int b) { return a + b; }
// Is partial application possible and how:
import std.functional;
alias foo6b = partial!(foo6, 5);
assert(foo6b(6) == 11);
}

View file

@ -0,0 +1,30 @@
void main() {
// Function definition
// See the "Function definition" task for more info
void noArgs() {}
void fixedArgs(int arg1, int arg2) {}
void optionalArgs([int arg1 = 1]) {}
void namedArgs({required int arg1}) {}
int returnsValue() {return 1;}
// Calling a function that requires no arguments
noArgs();
// Calling a function with a fixed number of arguments
fixedArgs(1, 2);
// Calling a function with optional arguments
optionalArgs();
optionalArgs(2);
// Calling a function with named arguments
namedArgs(arg1: 1);
// Using a function in statement context
if (true) {
noArgs();
}
// Obtaining the return value of a function
var value = returnsValue();
}

View file

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

View file

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

View file

@ -0,0 +1 @@
foo(1, 2, 3, 4, 5)

View file

@ -0,0 +1,3 @@
writeLn('Hello world.');
foo;
writeLn('Goodbye world')

View file

@ -0,0 +1 @@
myMethod()

View file

@ -0,0 +1 @@
myMethod(97, 3.14)

View file

@ -0,0 +1,2 @@
func foo() { }
foo()

View file

@ -0,0 +1,3 @@
//There is no difference between subroutines and functions:
func foo() { } //doesn't explicitly return something (but in fact returns nil)
func bar(x) { return x * 2 } //explicitly returns value (keyword "return" can be omitted)

View file

@ -0,0 +1 @@
//All arguments are passed by reference

View file

@ -0,0 +1,15 @@
//Using a closure:
func apply(fun, fst) { snd => fun(fst, snd) }
//Usage:
func sum(x, y) { x + y }
var sum2 = apply(sum, 2)
var x = sum2(3) //x is 5
//By second argument
func flip(fun) { (y, x) => fun(x, y) }
func sub(x, y) { x - y }
var sub3 = apply(flip(sub), 3)
x = sub3(9) //x is 6

View file

@ -0,0 +1,2 @@
func foo(x, y, z) { }
foo(1, 2, 3)

View file

@ -0,0 +1,2 @@
func foo(x, y = 0, z = 1) { }
foo(1)

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