我已经在 exercism.io 上完成了 strains
练习。我正在重构我的解决方案。对于上下文:Ints.Keep
接受一个谓词函数,并为谓词函数为真的每个元素返回一个经过过滤的 Ints 类型 slice 。相反地,Discard 返回谓词不为真的所有元素。 Discard 返回 Keep 的倒数。我是这样实现的:
func (i Ints) Keep(pred func(int) bool) (out Ints) {
for _, elt := range i {
if pred(elt) {
out = append(out, elt)
}
}
return
}
func (i Ints) Discard(f func(int) bool) Ints {
return i.Keep(func(n int) bool { return !f(n) })
}
现在我想稍微清理一下。我要创建:
type Predicate func(int) bool
然后我想在输入为 Predicate
的地方实现 Keep 和 Discard。当我尝试在 Discard 中创建匿名函数以返回 Keep 时遇到问题:
func (i Ints) Discard(p Predicate) Ints {
return i.Keep(Predicate(n int) { return !p(n) })
}
这可能吗?我找不到创建命名 func 类型的匿名函数的方法。
最佳答案
您可以通过将匿名函数转换为 Predicate
来实现,如下所示:
func (i Ints) Discard(p Predicate) Ints {
return i.Keep(Predicate(func(i int) bool { return !p(i) }))
}
这不是我想要的那么干净,但我打赌这是最好的。
关于GoLang 实现自定义类型的匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55961456/