-
Notifications
You must be signed in to change notification settings - Fork 1
Function
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: 11func double(a) {
return a * 2
}
func apply_and_add1(fun, value){
return fun(value) + 1
}
myFun := apply_and_add1
print( myFun(double, 3) ) // OUTPUT: 7Function returns null by default if there is no value returned.
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
*/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) )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: 5In such case, if a function name is given, the name will be ignored.
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: 3YJLO 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: 7Every 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 ) // ErrorAssigning 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: 3To learn more advanced topics about function member reference, please read the OOP section.
Get the function name
Get input arguments as a list
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