函数式编程

package main

import (
    "bufio"
    "fmt"
    "io"
    "strings"
)

type intGen func() int  //正规的函数式编程都是先定义函数类型

func fibonacci() intGen {  //声明一个返回intGen类型的斐波那契生成器
    a, b := 0, 1
    return func() int {
        a, b = b, a+b
        return a
    }
}
func (g intGen) Read(p []byte) (n int, err error) { //为函数实现io.Reader的Read接口
    next := g()
    if next > 10000 {   //因为是斐波那契额数列,所以取不完,所以设置让他取完
        return 0, io.EOF
    }
    s := fmt.Sprintf("%d\n", next)
    return strings.NewReader(s).Read(p)
}

func printFileContents(reader io.Reader) {  //因为实现了io.Reader的方法所以可以将函数直接传入
    scanner := bufio.NewScanner(reader)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
}

func main() {
    f := fibonacci()
    printFileContents(f)
}




posted @ 2019-12-19 19:36  离地最远的星  阅读(94)  评论(0编辑  收藏  举报