定義
函數(shù)式編程"是一種"編程范式"(programming paradigm),也就是如何編寫程序的方法論
特性
函數(shù)是一等公民: 參數(shù), 變量, 返回值都可以是函數(shù);
只用"表達式", 不用"語句";
-
高階函數(shù)和閉包;
image.pngfunc adder() func(int) int { sum := 0 return func(v int) int { sum += v return sum } } 不修改狀態(tài);
遞歸
應(yīng)用
斐波那契數(shù)列
func fibonacci() func() int {
a, b := 0, 1
return func() int {
a, b = b, a + b
return a
}
}
func main() {
f := fibonacci()
fmt.Println(f()) // 1
fmt.Println(f()) // 1
fmt.Println(f()) // 2
fmt.Println(f()) // 3
fmt.Println(f()) // 5
fmt.Println(f()) // 8
fmt.Println(f()) // 13
}
為函數(shù)聲明接口
// 定義類型
type intGen func() int
func (g intGen) Read(p []byte) (n int, err error){
next := g()
if next > 10000 {
retrun 0, io.EOF
}
s := fmt.Sprintf("%d\n", next)
return strings.NewReader(s).Read(p) // 代理 Read
}
func printFileContents(reader io.Reader) {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
func main() {
f := fibonacci()
printFileContents(f)
}
// 結(jié)果
1
1
2
3
.
.
.
4181
6765
使用函數(shù)遍歷二叉樹
修改下遍歷節(jié)點的代碼.
-
tree/node原內(nèi)容package tree import "fmt" type Node struct { Value int Left, Right *Node } func CreateNode(value int) *Node { return &Node{Value: value} } func (node Node) Print() { fmt.Println(node.Value) } func (node *Node) SetValue(value int) { node.Value = value } func (node *Node) Traverse() { node.TraverseFunc(func(no *Node) { no.Print() }) fmt.Println() } -
同級目錄新建文件
travelsal.gopackage tree import "fmt" // 接口, 這個函數(shù)是從上面拿下來的 func (node *Node) Traverse() { node.TraverseFunc(func(no *Node) { no.Print() }) fmt.Println() } // 將函數(shù)作為參數(shù) func (node *Node) TraverseFunc(f func(*Node)) { if node == nil { return } node.Left.TraverseFunc(f) f(node) node.Right.TraverseFunc(f) }
優(yōu)點
- 代碼簡潔, 開發(fā)快速
- 更為自然, 不需要修飾如何訪問自由變量
- 接近自然語言, 易于理解
- 更方便的代碼管理
- 易于"并發(fā)編程"
- 代碼的熱升級