0

while browsing for a contains method, I came across the following Q&A

contains-method-for-a-slice

It is said time and again in this Q&A that the method is really trivial to implement. What I don't understand is, if it were so easy to implement, and seeing how DRY is a popular software principle && and most modern languages implement said method , what sort of design reasoning could be involved behind the exclusion of such a simple method?

Community
  • 1
  • 1
metric-space
  • 541
  • 4
  • 14

2 Answers2

4

The triviality of the implementation depends on the scope of the implementation. It is trivial to implement when you know how to compare each value. Application code usually knows how to compare the types used in that application. But it is not trivial to implement in the general case for arbitrary types, and that is the situation for the language and standard library.

ChrisH
  • 4,788
  • 26
  • 35
  • 1
    This is not the reason. The language does [implement comparison for types where it makes sense](https://golang.org/ref/spec#Comparison_operators). –  Dec 18 '14 at 21:08
3

Figuring out if a slice contains a certain object is an O(n) operation where n is the length of the slice. This would not change if the language provided a function to do this. If your code relies on frequently checking if a slice contains a certain value, you should reevaluate your choice of data structures; a map is usually better in these kind of cases. Why should the standard library include functions that encourage you to use the wrong data structure for the task you have?

fuz
  • 88,405
  • 25
  • 200
  • 352
  • One of go's main aims is to promote the use of peopper software principles. Not sure if I'm allowed to use another language's feature I found convenient, but given what you said, is Python's 'in' operator a promoter of wrong usage ? – metric-space Dec 18 '14 at 20:03
  • I'm not sure what Python's `in` operator does as I don't speak Python. I believe that it's not improper though; if it is overloadable—like all (?) Python operators, it sounds like a good idea to have it. You should just reevaluate your data structures if you need to use it often on slices. – fuz Dec 18 '14 at 20:07
  • It is not always about time complexity. `n` doesn't matter when all you have to is check if an element is one of those 3 elements you wanna skip your loop for. – Ashvin Sharma Jul 16 '20 at 05:58