initial commit
This commit is contained in:
commit
493ce92e02
62 changed files with 1213 additions and 0 deletions
30
recursion/recursion.go
Normal file
30
recursion/recursion.go
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
//this calls itself until it reaches the base case of fact(0)
|
||||
func fact(n int) int {
|
||||
if n == 0 {
|
||||
return 1
|
||||
}
|
||||
return n * fact(n-1)
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println(fact(7))
|
||||
|
||||
// closures can also be recursive,
|
||||
// but this requires the closure to be declared with
|
||||
// a typed var explicitly before its defined
|
||||
var fib func(n int) int
|
||||
|
||||
fib = func(n int) int {
|
||||
if n < 2 {
|
||||
return n
|
||||
}
|
||||
return fib(n-1) + fib(n-2)
|
||||
}
|
||||
|
||||
//simce fib was previously declared in main Go knows which function to call with fib here
|
||||
fmt.Println(fib(7))
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue