Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the lenght of a vector idiomatically

Tags:

go

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?

like image 659
Matt Joiner Avatar asked Nov 25 '10 15:11

Matt Joiner


2 Answers

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

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

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

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.

like image 62
13 revs Avatar answered Oct 18 '22 17:10

13 revs


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

like image 28
uriel Avatar answered Oct 18 '22 18:10

uriel