GoLang's Type System

I’m looking for some links to explain(hopefully in simplistic terms) GoLang’s type system.

I can use GoLang’s type system but I find that I’m guessing at what is possible with GoLang’s type system when I start venturing off the beaten path.

Example: I tried solving a problem(below) that creates lazy fibonacci generator.

Basic fibonacci function(fib)

func fib(n uint) uint {
	if n == 0 {
		return 0
	} else if n == 1 {
		return 1
	} else {
		return fib(n-1) + fib(n-2)
	}
}

Create a type to help with the lazy fibonacci generator function.

type Func[T any] func() (T, Func[T])//doesn't need to be generic but what the heck!

The generator function which returns the calculated fibonacci element and a function which returns the next fibonacci element and the generator function for the (next + 1)…etc

func cal_fib_elem_and_next(n uint) (uint, Func[uint]) {
	return fib(n), Func[uint](func() (uint, Func[uint]) { return cal_fib_elem_and_next(n + 1) })
}

Usage.

func main() {
	n, next_func := cal_fib_elem_and_next(20)
	fmt.Printf("elem: %d, %T\n", n, next_func)
	n, next_func = next_func()
	fmt.Printf("elem: %d, %T\n", n, next_func)
	n, next_func = next_func()
	fmt.Printf("elem: %d, %T\n", n, next_func)
	n, next_func = next_func()
	fmt.Printf("elem: %d, %T\n", n, next_func)
}

Output:

I arrived at this solution by just trying(guessing) it… I didn’t know(before hand) if GoLang’s type system would handle this.

I find that GoLang’s type system is well documented when you are on the beaten path but as soon as you are off that beaten path… You are on your own.

Well there’s this The Go Programming Language Specification - The Go Programming Language, but it has not got a lot of exposition or simplistic terms. It does cover everything.

Whenever I see Fibonacci generators, it’s usually part of FP tutorials, and although Go has first class functions, it isn’t really intended for the style of programming you’d do in proper FP languages. It has no tail call optimization, for instance.

1 Like

As someone unfamiliar with FP programming languages, I’m not sure what you’re looking for that’s not covered in the language specification. Your example looks like it would work, but could have potentially huge performance impact. I think that the closure you return is a separate memory allocation and like @mje said, Go doesn’t have tail call optimization.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.