Function type in Gox language-GX9.1

The function type is a special data type that represents a function that can be called in a computer language.

Gox language in spring

In the Gox language, the function type is defined like this.

myAdd = fn(a, b) {
	return a + b + b
}

c = myAdd(3, 5)

println(c)

upperPrintln = fn(s ...) {
	for _, v = range(s) {
		if typeOf(v) == "string" {
			print(tk.ToUpper(v))
		} else {
			printf("%v", v)
		}
	}

	println()
}

upperPrintln("a", "bcd", 123)

sum = fn(n...) {
	t = 0
	for _, a = range(n) {
		t += a
	}
	return t
}

println(sum(1, 2, 3, 1.8))

println2 = fn(s...) {
	println(s...)
	println(s)
	println()
}

println2(1, "abc", 2.6, true)

println2(myAdd(2.9 ,7.1))


The result is like this.

λ gox -gopath functionType
13
ABCD123
7.8
1 abc 2.6 true
[1 abc 2.6 true]

17.1
[17.1]

Among them, the myAdd function is a variable of a function type defined by itself, accepts two parameters a and b, and calculates the result of a+b+b. The upperPrintln function accepts any number of parameters, converts them to uppercase and outputs them one by one. The sum function simply accepts any number and calculates the sum of them. The keyword fn is used to define functions in the Gox language, and it is also compatible with the func keyword.

Note that the variable number of parameters is represented by an ellipsis..., if you want to traverse it, use for...range... loop, if you want to pass it directly to other functions with variable length parameters, use s... Just enter, the println2 function in this example demonstrates the method of such a transfer, this function is very simple, it outputs a carriage return and line feed more than the println function.

Note that in the println2 function, it also demonstrates the direct output of variable-length parameters, which proves that it is passed in a slice (array).

* Note: Since the 0.995 version, Gox has supported the general func add(a, b) method of defining functions, so the following content is invalid and is only reserved for reference to the old version.

In addition, it is important to note that there is no ordinary function definition method in general languages ​​in the Gox language (except when defining methods of object classes), for example:

fn myAdd(a, b) {
  return a + b + b
}

can only be:

myAdd = fn(a, b) {
  return a + b + b
}

Or use anonymous functions, for example:

 fn(a, b) {
  return a + b + b
}(3, 4)

Guess you like

Origin blog.csdn.net/weixin_41462458/article/details/107787884
Recommended