Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make this Fibonacci sequence generator more elegant?

Tags:

go

package main

import "fmt"

func fib_seq() func() int {
    n0, n1 := 0, 1

    return func() int {
        result := n0
        n0, n1 = n1, n0 + n1
        return result
    }
}

func main() {
    f := fib_seq()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}

This is my Fibonacci sequence generator. The definition of result is unwanted (but necessary).

I wonder is there a way to execute x, y = y, x + y after return?

like image 985
zentoo Avatar asked Nov 25 '25 20:11

zentoo


2 Answers

You may want to take a look at defer:

func fib_seq() func() int {
    n0, n1 := 0, 1

    return func() int {
        defer func() {
            n0, n1 = n1, n0 + n1
        }()

        return n0
    }
}
like image 80
Rahn Avatar answered Nov 27 '25 15:11

Rahn


Named return. But what you have is already readable enough.

func fib_seq() func() int {
    n0, n1 := 0, 1

    return func() (r int) {
        r, n0, n1 = n0, n1, n0 + n1
        return
    }
}
like image 39
abhink Avatar answered Nov 27 '25 14:11

abhink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!