3 ms·
There are two bugs in the code, and your (intentional?) use of non-idiomatic Go is the cause of one of them. Since you don't mention it in your follow-up commen
by morelisp 5y ago
There are two bugs in the code, and your (intentional?) use of non-idiomatic Go is the cause of one of them. Since you don't mention it in your follow-up comment I assume you didn't mean to write it in the first place.
Still, there is a middle ground that remains both efficient and readable:
sum := 0
for _, v := range take(20, nums) {
if v % 2 == 1 { // or if odd(v), if you like
sum += v
}
}
I'd venture most of the clarity come from the generic take (specifically, being able to implicitly take min(len(nums), 20)), not the generic filter/reduce. The second point of clarity comes from Ruby's dynamic method dispatch and large method set on numeric types; no thanks. Only as a third-tier aspect does select/reduce come into play, and I think that one is much more questionable (e.g. reduce or fold, and either way how do I explain this name to new programmers? -- and &:+, what a messy identifier).