Skip to content

Function

Liu Siwei edited this page Nov 19, 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() {
	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
}

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

Function returns null by default if there is no value returned.

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.

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() {
	count := 0
	return func() {
		count += 1
		print( count )
	}
}

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() {
	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(){
	a := 2
	return func(){}
}

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.

Special attribute

$name

Get the function name

$args

Get input arguments as a list

Special Methods

$apply

Call a function with arguments provided as an array

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