【发布时间】:2019-05-02 23:27:40
【问题描述】:
我已经在 exercism.io 上完成了 strains 练习。我正在重构我的解决方案。对于上下文:Ints.Keep 接受一个谓词函数,并为谓词函数为真的每个元素返回一个 Ints 类型的过滤切片。相反,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 的保留和丢弃。当我尝试在 Discard 中创建匿名函数以返回 Keep 时遇到了问题:
func (i Ints) Discard(p Predicate) Ints {
return i.Keep(Predicate(n int) { return !p(n) })
}
这可能吗?我找不到创建命名函数类型的匿名函数的方法。
【问题讨论】:
标签: go anonymous-function