File: functions.adoc

package info (click to toggle)
nickle 2.107
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 3,756 kB
  • sloc: ansic: 27,954; yacc: 1,874; lex: 954; sh: 204; makefile: 13; lisp: 1
file content (62 lines) | stat: -rw-r--r-- 1,527 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
= Nickle Functions

An example function might be declared like this: 

----
int gcf ( int a, int b ) {
        int f = 1;
        for ( int i = 2; i <= abs ( a ) && i <= abs ( b ); ++i )
                while ( ( a // f ) % i == 0 && ( b // f ) % i == 0 )
                        f *= i;
        return f;
}
----

First comes the return type of the function, then the function name,
then the list of arguments (with types), and finally the statement
list in curly braces.  If any types are left off, Nickle assumes
``poly``.  In any case, all typechecking is done at runtime.

A function can take any number of arguments.  The final argument may
be followed by an ellipses ( `+...+` ) to indicate an arbitrary,
variable number of succeeding arguments, each of the type of the final
argument; the last argument becomes an array to store them.

----
> print sum
int sum (int a, int b ...)
{
    for (int i = 0; i  dim (b); ++i)
        a += b[i];
    return a;
}
> sum(1,2)
3
> sum(4)
4
> sum(1,2,4,6)
13
----

Functions are called as in C, with their names followed by argument values in parentheses: 

----
foo ( "hello", 7.2 );
----

Since they are first class, functions can be assigned: 

----

int(int,int) a = gcf;
----

See the section on Copy semantics for details on what functions may be
assigned to each other. Functions may also be declared and used
anonymously:

----
(int func ( int a, int b ) { return a + b; })(2,3);     /* 5 */
----

Replacing the function name with the keyword `func` indicates its anonymity.