Every once in a while I get irritated by the edges in programming languages. One notorious edge is the absence or presence of a method on an object. The method is either there or it isn't and if you guess wrong you have a program that simply doesn't run.
In some programming languages, there is a way around this. You can hook into the runtime to generate a method on an object when it is called but doesn't yet exist. Of course, that leaves us with the decision of what method to generate. And, I suspect that some of you reading this are wondering now whether this is some sort of rabbit hole - what problem am I trying to solve? In most cases, the fact that a method doesn't exist is important. We shouldn't gloss over it. But, sometimes we can gain advantage when we do.
Consider finder methods. You have some criterion you want to use to find an object. Maybe some unique id. You call your finder and you have to deal with possibility that the thing you are looking for doesn't exist. Most of the time this means that you are obligated to use a null check in your language, but that's messy and people can easily forget to do it. Some functional programming languages get around this by using a Maybe or Option type, but there's another way to punt. You can make your finder always return a collection. If the thing you are looking for is not found, you receive an empty collection. "Okay," I can hear you say, "that is just passing the buck. You have to check later." The fact of the matter is that you may not have to. You could use a map to perform the same operation on each of the elements, provided there is no chance of having more than one.
This makes me wonder about something. What if we were were able to treat values as collections when we are programming?
Consider this in a dynamic language.
x = 4
When we type that, we expect that
x will yield an error, and we expect that
x would yield an error also. But what if they didn't? What if each of those references returned
4. What if values could be treated as infinite collections of themselves in programming? Could that be a creative way of erasing an edge?
Consider this in a Haskell-ish language.
map (+1) [1,2,3]
We know that would yield
Okay, how about this?
map (+1) 3
Couldn't that evaluate to
With an operation like map, this is easy. What about fold (codenamed reduce or inject in some languages)?
If we did something like:
[0,1,2].reduce(:+) in Ruby, we'd expect the sum.
What should we expect for this?
The sensible answer is:
2. A case could be made for infinity as it is the sum of an infinite list of 2s, but I think we can just say that it evaluates to
2 and maintain consistency.
Maybe there is an inconsistency in this and it all falls down. But I hope that it works and that there is an efficient way to merge scalar values and collections of the same value. I suspect I'm just reinventing APL in conventional programming languages.