我是 Go 的新手,为了练习我在 Exercism 上做了一些编码练习。我在一个特定的练习上绊倒了,在这个练习中我很难理解解决方案。这是代码:
// Ints defines a collection of int values
type Ints []int
// Lists defines a collection of arrays of ints
type Lists [][]int
// Strings defines a collection of strings
type Strings []string
// Keep filters a collection of ints to only contain the members where the provided function returns true.
func (i Ints) Keep(strainer func(int) bool) (o Ints) {
for _, v := range i {
if strainer(v) {
o = append(o, v)
}
}
return
}
// Discard filters a collection to only contain the members where the provided function returns false.
func (i Ints) Discard(strainer func(int) bool) Ints {
return i.Keep(func(n int) bool { return !strainer(n) })
}
我的问题来自 Discard 方法,我不明白花括号中的第二个 return 语句,因为 Keep 函数假设返回 Ints 类型的值而不是布尔语句,除非我错过了什么,如果有人可以分解 Discard 函数对我来说会很有帮助。谢谢
该Keep
方法将函数作为参数。它期望它是func (int) bool
- 一个接受 anint
并返回 a的函数bool
。
当在Keep
中调用时Discard
,代码传递给它一个带有正确签名的匿名函数(take int
, return bool
)。这个匿名函数调用strainer
(这是一个传递给 的函数Discard
)并返回它的响应,否定。
这个想法是strainer
一个过滤器函数:它告诉你要保留哪些元素。所以 的实现Keep
很简单:迭代所有元素,只保留那些strainer
返回 true 的元素。
Discard
使用 以巧妙的方式编写Keep
,而不是像这样编写循环:
func (i Ints) Discard(strainer func(int) bool) (o Ints) {
for _, v := range i {
if !strainer(v) {
o = append(o, v)
}
}
return
}
相反Keep
,它使用一个函数调用,该函数反转 的结果strainer
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句