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
"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 to share