英文:
pythons enumerate in go
问题
假设我有一个生成斐波那契数列的生成器,并且我想使用enumerate(get_next_fibs(10))
来生成索引和生成器中的数字的对。我在寻找使用“命名返回值”解决方案时遇到了困难。
以下是你提供的代码的翻译:
package main
import "fmt"
func get_next_fibs(ii int) func() int {
i := 0
a, b := 0, 1
fc := func() int {
i++
a, b = b, a+b
if ii <= i {
return -1
}
return a
}
return fc
}
func enumerate(iter func() int) func() (index, v int) {
index := 0
fc := func() (index, v int) {
v := iter()
return index, v
index++
}
return fc
}
func main() {
iter := enumerate(get_next_fibs(10))
// iter := get_next_fibs(10)
fmt.Printf("iter = %T\n", iter)
for tuple := iter(); tuple != -1; tuple = iter() {
fmt.Println("tuple:", tuple)
}
}
希望对你有帮助!
英文:
let's say that I have generator of fibonachi numbers, and I would like to use enumerate(get_next_fibs(10))
and I would like to have generator of pairs index, number_from_generator
, I am struggling to find solution with "named return values"
and it's not how it should be done but it's for purpose of learning specific things about generators
package main
import "fmt"
func get_next_fibs(ii int) func() int {
i := 0
a, b := 0, 1
fc := func() int {
i++
a, b = b, a+b
if ii <= i {
return -1
}
return a
}
return fc
}
func enumerate(iter func() int) func() (index, v int) {
index := 0
fc := func() (index, v int) {
v := iter()
return
index++
}
return fc
}
func main() {
iter := enumerate(get_next_fibs(10))
// iter := get_next_fibs(10)
fmt.Printf("iter = %T\n", iter)
for tuple := iter(); tuple != -1; tuple = iter() {
fmt.Println("tuple:", tuple)
}
}
答案1
得分: 2
这段代码样本中存在一些问题:
- 在return语句之后不能使用
index++
。如果你需要在返回后执行某些操作,可以使用defer
关键字。 - 你没有理解Go语言中的变量遮蔽机制,因此你试图修改错误的
index
变量。 - Go语言中没有元组的概念。
以下是修复后的代码样本:
...
func enumerate(iter func() int) func() (index, v int) {
counter := 0
return func() (index, v int) {
i := counter
counter++
return i, iter()
}
}
...
func main() {
iter := enumerate(get_next_fibs(10))
fmt.Printf("iter = %T\n", iter)
for {
i, v := iter()
if v == -1 {
break
}
fmt.Printf("i: %d, v: %d\n", i, v)
}
}
英文:
You have few issues in this code sample:
- You can't have
index++
after return statement. Usedefer
if you need to do something afterreturn
-ing. - You're missing how variable shadowing works in go. Thus, you're trying to modify a wrong
index
variable. - Go doesn't have tuples.
...
func enumerate(iter func() int) func() (index, v int) {
counter := 0
return func() (index, v int) {
i := counter
counter++
return i, iter()
}
}
...
func main() {
iter := enumerate(get_next_fibs(10))
fmt.Printf("iter = %T\n", iter)
for i, v := iter(); v != -1; i, v = iter() {
fmt.Printf("i: %d, v: %d\n", i, v)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论