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 ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.