Discussion:
[go-nuts] Recursive Closure Variable?
m***@gmail.com
2015-07-30 15:33:22 UTC
Permalink
I have a variable that I am assigning to a function. I would like to call
it recursively. Can I? Or do I have to move fold(int, int, int) out of
fold(string)?

func fold(chain string) (*Protein, error) {
cur, err := NewProtein(chain)
if err != nil {
return nil, err
}

best := cur.Copy()
bestScore := -20

fold := func(index, row, col int) {
cur.SetLocation(index, row, col)
if index >= cur.Len() - 1 {
score := cur.GetScore()
if score > bestScore {
bestScore = score
best = cur.Copy()
}
} else {
fold(index + 1, row + 1, col)
fold(index + 1, row, col + 1)
fold(index + 1, row - 1, col)
fold(index + 1, row, col - 1)
}
}

fold(0, cur.Len() - 1, cur.Len() - 1)
return best, nil
}

Thanks!
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Fredrik Ehnbom
2015-07-30 15:39:35 UTC
Permalink
The variable needs to be declared before you can reference it, i.e:

var fold func(index, row, col int)
fold = func(index, row, col int) {...}
Post by m***@gmail.com
I have a variable that I am assigning to a function. I would like to call
it recursively. Can I? Or do I have to move fold(int, int, int) out of
fold(string)?
func fold(chain string) (*Protein, error) {
cur, err := NewProtein(chain)
if err != nil {
return nil, err
}
best := cur.Copy()
bestScore := -20
fold := func(index, row, col int) {
cur.SetLocation(index, row, col)
if index >= cur.Len() - 1 {
score := cur.GetScore()
if score > bestScore {
bestScore = score
best = cur.Copy()
}
} else {
fold(index + 1, row + 1, col)
fold(index + 1, row, col + 1)
fold(index + 1, row - 1, col)
fold(index + 1, row, col - 1)
}
}
fold(0, cur.Len() - 1, cur.Len() - 1)
return best, nil
}
Thanks!
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
m***@gmail.com
2015-07-30 15:52:52 UTC
Permalink
Thank you very much! :)
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Continue reading on narkive:
Loading...