How to make this Fibonacci sequence generator more elegant?

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 is result

undesirable (but necessary).

I wonder if there is a way to execute x, y = y, x + y

after return

?

+3


source to share


4 answers


You can 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
    }
}

      

+2


source


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
    }
}

      

+2


source


Personally, I would prefer the following (for readability):

type fib struct{ n0, n1 int }

func (f *fib) next() int {
    defer func() { 
        f.n0, f.n1 = f.n1, f.n0+f.n1 
    }()
    return f.n0
}

func main() {
    fib := &fib{0, 1}
    for i := 0; i < 10; i++ {
        fmt.Println(fib.next())
    }
}

      

0


source


"Elegant" means different things to different people. For some it may mean "brevity" and for others it may mean "simplicity" or "readability".

Here's my example:

public class Fibonacci {

    private static int x;
    private static int y;
    private static int z;

    public static void main(String[] args) {
        x = 0;
        y = 1;
        z = 0;

        System.out.println(x);
        System.out.println(y);
        while (z < 100) {
            z = x + y;
            System.out.println(z);
            x = y;
            y = z;
        }

    }
}

      

As you can see, I prefer readability over complexity :)

0


source







All Articles