Studying Go language version 2 means that I tried to study algorithms with Go.
First of all, what is a closure, I will describe the sentence that I referred to below.
Go's anonymous function is a "closure". Closures are called "function closures" in Japanese, and are "confined (closures)" as a set of functions and "outside function" environments related to function processing.
So it represents an anonymous function. This time I started by using this to create a recursive function.
fact.go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
r := bufio.NewReader(os.Stdin)
w := bufio.NewWriter(os.Stdout)
defer w.Flush()
var a int
fmt.Fscan(r, &a)
result := solveFact(a)
fmt.Print(result)
}
func solveFact(x int) int {
var fact func(n int) int
fact = func(n int) int{
if n == 0{ return 1 }
return n * fact(n - 1)
}
return fact(x)
}
Execution result
❯ go run fact.go
4
24
fib.go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
r := bufio.NewReader(os.Stdin)
w := bufio.NewWriter(os.Stdout)
defer w.Flush()
var a int
fmt.Fscan(r, &a)
result := solveFib(a)
fmt.Print(result)
}
func solveFib(x int) int {
var fib func(n int) int
fib = func(n int) int{
if n <= 1{return n}
return fib(n -1) + fib(n - 2)
}
return fib(x)
}
Execution result
❯ go run fib.go
10
55
Fmt.Scan () / fmt.Printf () is used for input and output. However, I am afraid of the amount of input and output, so I use bufio and try to buffer it.
Recommended Posts