Skip to content

Function

Liu Siwei edited this page May 16, 2017 · 9 revisions

Functions can be passed as function parameters or returned by a function. A function is only visible after its definition.

func foo() {
	var a = 5;
	return a + 2 * 3;
}
print( foo() );	// OUTPUT: 11
func double(a) {
	return a * 2;
}

func apply_and_add1(fun, value){
	return fun(value) + 1;
}

var myFun = apply_and_add1;
print( myFun(double, 3) );	// OUTPUT: 7

Arguments

While applying a function, fewer arguments can be accepted, but the opposite does not.

func fun(a, b) {
	print(a);
	print(b);
}
fun(2);

/* OUTPUT:
a
null
*/

Recursion

Function recursion is supported in YJLO Script.

func fib(n) {
	if (n < 2) return n;
	return fib(n - 1) + fib(n - 2);
}

print( "Fib(9) = " + fib(9) );

Anonymous function

While using a function body as an expression, the function can be anonymous.

var sum = func (a, b) { return a+b; };
print( sum(2, 3) );	// OUTPUT: 5

In such case, if a function name is given, the name will be ignored.

Closure

A closure is a function having access to the parent scope, even after the parent function has closed.

func counter_closure() {
	var count = 0;
	return func() {
		count += 1;
		print( count );
	};
}

var counter = counter_closure();
counter();	// OUTPUT: 1
counter();	// OUTPUT: 2
counter();	// OUTPUT: 3

Function Member Reference

YJLO Script supports referencing function members from outside of the function with dot operator (.):

func fun() {
	var name = "sum";
	func sum(a, b) {
		return a+b;
	}
}

print( fun.name );		// OUTPUT: "sum"
print( fun.sum(3, 4) );		// OUTPUT: 7

Caveat

Every time a function member is referenced, the whole function is evaluated.

Private function memebers, including member fields and member functions, cannot be referenced from outside of the function. Prepending an underscore (_) to the member name to makes it private.

func fun(){
	_value = 10;
}
print( fun._value );	// Error

Assigning new values directly to function members is not supported. However, you can assign values to closure function members.

func A(){
	var a = 2;
	return func(){};
}

var myA = A();
print(myA.a);	// OUTPUT: 2

myA.a = 3;
print(myA.a);	// OUTPUT: 3

To learn more advanced topics about function member reference, please read the OOP section.

Introduction

Langauge Guide

Libraries

  • Utility
    • ListUtil
    • StringUtil
    • Math
  • Data Structure
    • LinkedList
    • Stack
    • Heap
    • HeapList
    • HashMap
    • HashSet
  • Others
    • UnitTest
    • Tokenizer

Dev Reference

  • Syntax Sugar
Clone this wiki locally