2017-05-29 17 views
3
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()) 
    } 
} 

這是我的斐波那契序列發生器。 result的定義是不需要的(但是必要的)。如何讓這個斐波那契序列發生器更優雅?

不知有沒有辦法在return之後執行x, y = y, x + y

+0

你可以做'defer'但它是醜陋的。 – zerkms

+0

請參閱golang.org上的[示例](https://play.golang.org/p/A0nH96VB4S) –

+0

您所做的很不錯。斐波納契計算有另一種方法。你可以使用矩陣來做到這一點。從編程觀點來看,它不太優雅,但從數學的角度來看它更加優雅。我有一個Python實現的例子https://gist.github.com/I159/ab818dfe0415d415d7314c57e17f0460#file-matrix_fibo-py-L62-L106。如果你覺得這很有趣,我可以把它翻譯成Go。 – I159

回答

2

你可能想看看defer

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

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

     return n0 
    } 
} 
2

命名的回報。但是你擁有的已經足夠可讀。

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

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

就個人而言,我寧願以下(爲便於閱讀):

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

「優雅」 意味着不同的事情不同的人。對某些人來說,它可能意味着「簡潔」,對其他人來說,它可能意味着「簡單」或「可讀性」。

這裏是它我採取:

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

    } 
} 

正如你所看到的,我喜歡的可讀性在複雜:)

+0

我同意你的觀點......你只是沒有在'Go'中做:) – alexbt