Reputation: 586
I have the following code
func Sum(a []int) int {
res := 0
for _, n := range a {
res += n
}
return res
}
func SumAll(ns ...[]int) (sums []int) {
for _, s := range ns {
sums = append(sums, Sum(s))
}
return
}
//SumAllTails sums [:1] in each slice
func SumAllTails(sls ...[]int) []int {
newsls := [][]int{}
for _, sl := range sls {
newsls = append(newsls, sl[1:])
}
return SumAll(newsls...)
}
Ideally I'd like to change the last function to be something like this
func SumAllTails(sls ...[]int) []int {
return SumAll(sls[:][1:]...)
}
This last bit returns each slice but the first one, but what I'd like to do is unpack each slice from position 1 onwards, omitting the value at 0. Is there a way of achieving this in go?
Upvotes: 1
Views: 74
Reputation: 51512
I think the only way to do what you want without going through the slices first is to write a SumAlln function:
func SumAlln(n int, ns ...[]int) (sums []int) {
for _, s := range ns {
sums = append(sums, Sum(s[n:]))
}
return
}
func SumAll(ns...[]int) []int {
return SumAlln(0,ns...)
}
And then call SumAlln
.
Upvotes: 3