Below code in python:
def print_all(x):
print(x)
return print_all
allows to call print_all(1)(2)
or print_all(1)(2)(3)(4)
Edit
Another example in python:
def print_sums(x):
print(x)
def next_sum(y):
return print_sums(x+y)
return next_sum
print_sums(1)(3)(5)
which maps to syntax:
package main
import "fmt"
type printsumfunctype func(x int) printsumfunctype
func printSums(x int) printsumfunctype {
fmt.Println(x)
var nextSum func(y int) printsumfunctype
nextSum = func(y int) printsumfunctype {
return printSums(x + y)
}
return nextSum
}
func main() {
printSums(1)(2)(3)
}
In GoLang, function is first class
1) What is the syntax to self reference a function in GoLang?
2) What is the preferred naming convention to define types like printsumfunctype
?
You define a recursive function type:
type Printer func(interface{}) Printer
func printAll(x interface{}) Printer {
fmt.Println(x)
return printAll
}
func main() {
printAll(1)("Hello")
}
For the new code, you would write
type Sink func(int) Sink // not really different, is it?
func printSums(x int) Sink {
fmt.Println(x)
return func(y int) Sink {
return printSums(x + y)
}
}
A useful naming convention is to just name the types after their functions. In both of these cases, Printer
(basically function verb + "er") works. Or, the more generic term Sink
also fits, as it's a black hole that you can just keep dumping items into. I don't think there's any rule for it; these types aren't very common. Just pick a descriptive name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With