以惯用方式返回向量的长度

huangapple go评论85阅读模式
英文:

Returning the lenght of a vector idiomatically

问题

我正在编写一个返回可变长度数字序列的函数:

func fib(n int) ??? {
    retval := ???
    a, b := 0, 1
    for ; n > 0; n-- {
        ??? // 在这里将 a 添加到 retval
        c := a + b
        a = b
        b = c
    }
}

可以观察到返回序列的最终长度将为 n。为了实现符合 Go 语言惯用法,fib 应该如何返回?如果事先不知道长度,返回值和使用方式会有什么不同?如何将值插入到 retval 中?

英文:

I'm writing a function that returns a sequence of numbers of variable length:

func fib(n int) ??? {
    retval := ???
    a, b := 0, 1
    for ; n > 0; n-- {
        ??? // append a onto retval here
        c := a + b
        a = b
        b = c
    }
}

It can be observed that the final length of the returned sequence will be n. How and what should fib return to achieve idiomatic Go? If the length was not known in advance, how would the return value, and usage differ? How do I insert values into retval?

答案1

得分: 7

这里,我们知道有多少个数字;我们想要n个斐波那契数。

package main

import "fmt"

func fib(n int) (f []int) {
    if n < 0 {
        n = 0
    }
    f = make([]int, n)
    a, b := 0, 1
    for i := 0; i < len(f); i++ {
        f[i] = a
        a, b = b, a+b
    }
    return
}

func main() {
    f := fib(7)
    fmt.Println(len(f), f)
}

输出:7 [0 1 1 2 3 5 8]


这里,我们不知道有多少个数字;我们想要所有小于或等于n的斐波那契数。

package main

import "fmt"

func fibMax(n int) (f []int) {
    a, b := 0, 1
    for a <= n {
        f = append(f, a)
        a, b = b, a+b
    }
    return
}

func main() {
    f := fibMax(42)
    fmt.Println(len(f), f)
}

输出:10 [0 1 1 2 3 5 8 13 21 34]


你也可以使用Go的向量包中的IntVector。注意type IntVector []int

英文:

Here, we know how many numbers; we want n Fibonacci numbers.

package main

import &quot;fmt&quot;

func fib(n int) (f []int) {
	if n &lt; 0 {
		n = 0
	}
	f = make([]int, n)
	a, b := 0, 1
	for i := 0; i &lt; len(f); i++ {
		f[i] = a
		a, b = b, a+b
	}
	return
}

func main() {
	f := fib(7)
	fmt.Println(len(f), f)
}

Output: 7 [0 1 1 2 3 5 8]


Here, we don't know how many numbers; we want all the Fibonacci numbers less than or equal to n.

package main

import &quot;fmt&quot;

func fibMax(n int) (f []int) {
	a, b := 0, 1
	for a &lt;= n {
		f = append(f, a)
		a, b = b, a+b
	}
	return
}

func main() {
	f := fibMax(42)
	fmt.Println(len(f), f)
}

Output: 10 [0 1 1 2 3 5 8 13 21 34]


You could also use IntVector from the Go vector package. Note that type IntVector []int.

答案2

得分: 1

不要使用Vectors,使用slices。这里有一些将各种vector操作映射为惯用的slice操作的方法

英文:

Don't use Vectors, use slices. Here are some mapping of various vector operations to idiomatic slice operations.

huangapple
  • 本文由 发表于 2010年11月25日 23:42:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/4278715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定