A Concrete Example: Sorting
Let’s look at various types for a sort routine/method/function. We’ll look at how this is handled in several languages and consider what the type is saying. Obviously, these library routines are reliable; the point here is what the types can tell us or help us do.
-
Ruby: The types in Ruby don’t say much, maybe just to indicate what can be sorted by virtue of some object being able to respond to a method called sort. There’s a general expectation (though no requirement) that sorting will return an Array. We will, however, get runtime exceptions if the sorting can’t proceed—for example, with [2, "a"].sort, it won’t permit comparisons of Fixnum and String, or my personal favorite gotcha, [[], nil].sort.
-
C: C allows ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access