Making Map Operations Implicit in Programming

Michael Feathers
December 17, 2013

Every once in a while a couple of ideas come together. I was running a workshop on error handling the other day and over the course of it we started discussing the Maybe monad and Scala's Option type. I put this example from the Scala docs up on the screen:

val name: Option[String] = request getParameter "name"
val upper = name map { _.trim } filter { _.length != 0 } 
                                   map { _.toUpperCase }
println(upper getOrElse "")

We talked about how Option is very much like a collection that is constrained to have either 0 or 1 elements. An attendee mentioned that he didn't like Option for that reason - Option expressions look deceptive because they look like they are working against a collection rather than just a single element.

Immediately, my thoughts went back to APL and J. I'd been mentioning earlier that one of the things that is interesting about those languages is that most of their operations are polymorphic against the shape of data. The factorial operator in J works not only against a scalar like this:

! 5

But it can also be used against a vector like this:

! 5 4 8

The '!' operator can be used on scalars, vectors, and matrices of arbitrary rank and dimension - in each case it computes the factorial of its argument or its argument's sub-elements.

One side effect of this is that maps are not explicit in APL and J - they are implicit. That made me wonder - can they be implicit in other languages too? Can variables in many cases just be treated as collections of arbitrary dimension?

Imagine the Scala example in a language with implicit maps. It could look something like this:

val upper = name.trim.filter{ _.length != 0 }.toUpperCase
println(upper getOrElse "")

The filter still makes it apparent that we are dealing with something collection-ish, but in everything else, the expression is shape polymorphic. The trim can apply to an arbitrarily shaped collection of strings - toUpperCase can also.

What would our languages look like if we made them shape polymorphic?

If we moved in that direction it would be like baking the Composite Design Pattern deeply into language machinery. It could be very powerful.

Join the conversation on Hacker News: https://news.ycombinator.com/item?id=6921394

© 2014 Michael Feathers