Stream of consciousness: iterables instead of numbers
Intro
As I was working on LInQer I was hooked on the multiple optimizations that I was finding. Do you want to compute the average of an iterable? You would need the total count and the sum of the items, which you can get in a single function that you can reuse to get the sum or the count. But what if the iterable is an integer range between 1 and 10? Then you can compute the sum and you already know the count. Inspired by that work and by other concepts like interval types or Maybe/Nullable types, I've decided to write this post, which I do not know if it will lead to any usable code.
What is an iterable/enumerable?
In Javascript they call it an Iterable, in .NET you have IEnumerable. They mean the same thing: sources of values. With new concepts like async/await you can use Observables as Enumerables as well, although they are theoretically diametrically opposing patterns. In both languages they are implemented as having a method that returns an iterator/enumerator, an object that can move to the next value, give you the next value and maybe reset itself. You can define any stream of values like that, having one or more values or, indeed, none. From now own I will discuss in terms of .NET nomenclature, but I see no reason why it wouldn't apply to any other language that implements this feature.
For example an array is defined as an IEnumerable<T>
in .NET. Its enumerator will return false if trying to move to the next value and the array is empty, or true if there is at least a value and the current value will return the first value in the array. Move next again and it will return true or false depending on whether there is a next value. But there is no need for the values to exist to have an Enumerable. One could write an object that would return all the positive integer numbers. It's length would be infinite and the values would only be generated when requested. There is no differentiation between an Enumerable and a generator in .NET, but there is in Javascript. For this reason whenever I will use the term generator, I will mean an object that generates values rather than produce them from a source of existing ones.
The NULL controversy
A very popular InfoQ post describes the introduction of the NULL concept in programming languages a the billion dollar mistake. I am not so sure about that, but I can concede they make good points. The alternative to using a special value to describe the absence of a value is use an "option" object that either has Some value or it has None. You would check the existence of a value by calling a method to tell you if it has a value and you would get the value from the current value property. Doesn't it sound familiar? It's a more specific case of an Enumerator! Another popular solution to remove NULLs from code is to never return values from your methods, but arrays. An empty array would represent no value. An array is an Enumerable!
And that last idea opens up an interesting possibility: instead of one or none, you can have multiple values. What then? What would a multiplication mean? What about a decision block?
The LInQer experience
If you know me, you are probably fed up with me plugging LInQer as the greatest thing since fire was invented. But that's because it is! And while implementing .NET LInQ as a Javascript library I've played with some very interesting concepts.
For example, while implementing the Last operator on enumerables, I had two different implementations depending on whether one could know the length in advance and one could use indexed access to the values. An array of one billion values has no problem giving you the last item in it because of two things: you know where the array ends and you can access any item at any position without having to go through other values. You just take the value at index one billion minus one. If you would have a generator, though, the only way to get the last value would be to enumerate again and again and again and only when moving to the next value would fail you would have the last value as the last one. And of course, this would be bad if there are no bounds to the generator.
But there is more. What about very common statistical values like the sum? This, of course, applies to numbers. The Enumerable need not produce numbers, so in other contexts it means nothing. Then there are concepts like statistical distribution. One can make some assumptions if they know the distribution of values. A constant yet infinite generator of numbers will always have the same average value. It would return the same value, regardless of index.
I spent a lot of time doing sorting that only needs a part of the enumerable, or partial sorting. I've implemented a Quicksort algorithm that works faster than the default sort when there are enough values and that can ignore the parts of the array that I don't need. Also, there are specific algorithm to return the last or first N items. All of this depends on functions that determine the order of items. Randomness is also interesting, as it needs to take into consideration the change of probabilities as the list of items increases with each request. Sampling was fun, too!
Then there were operators like Distinct or Group which needed to use functions to determine sameness.
With all this work, I've never intended to make this more than what LInQ is in .NET: a way to dynamically filter and map and enumerate sequences of items without having to go through them all or to create intermediate but unnecessary arrays. What I am talking about now is taking things further and deeper.
Continuous intervals
What if the Enumerable abstraction is not enough? For example one could define the interval of real numbers between 0 and 1. You can never enumerate the next value, but there are definite boundaries, a clear distribution of values, a very obvious average. What about series and limits? If a generator generates values that depend on previous values, like a geometric progression or a Fibonacci series, you can sometimes compute the minimum or maximum value of the items in it, or of their sums.
Tools
So we have more concepts in our bag now:
- move next (function)
- current value
- item length (could be infinite or just unknown)
- indexed access (or not)
- boundaries (min, max, limits)
- distribution (probabilities)
- order
- discreteness
How could we use these?
Concrete cases
There is one famous probabilities problem: what are the chances you will get a particular value by throwing a number of dice. And it is interesting because there is a marked difference between using one die or more. Using at least two dice and plotting the values you get after multiple throws you get what is called a Normal distribution, a Gauss curve, and that's because there are more combinations of values that sum up to 6 than there are for 2.
How can we declare a value that belongs to an interval? One solution is to add all kinds of metadata or validations. But what if we just declare an iterable with one value that has a random value between 1 and 6? And what if we add it with another one? What would that mean?
Here is a demo example. It's silly and it looks too much like the Calculator demos you see for unit testing and I really hate those, but I do want to just demo this. What else can we do with this idea? I will continue to think about it.
class Program
{
static void Main(string[] args)
{
var die1 = new RandomGenerator(1, 6);
var die2 = new RandomGenerator(1, 6);
// just get the value
var value1 = die1.First() + die2.First();
// compose the two dice using Linq, then get value
var value2 = die1.Zip(die2).Select(z => z.First + z.Second).First();
// compose the two dice using operator overload, then get value
var value3 = (die1 + die2).First();
var min = (die1 + die2).Min();
}
/// <summary>
/// Implemented Min alone for demo purposes
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IGenerator<T> : IEnumerable<T>
{
int Min();
}
/// <summary>
/// Generates integer values from minValue to maxValue inclusively
/// </summary>
public class RandomGenerator : IGenerator<int>
{
private readonly Random _rnd;
private readonly int _minValue;
private readonly int _maxValue;
public RandomGenerator(int minValue, int maxValue)
{
_rnd = new Random();
this._minValue = minValue;
this._maxValue = maxValue;
}
public static IGenerator<int> operator +(RandomGenerator gen1, IGenerator<int> gen2)
{
return new AdditionGenerator(gen1, gen2);
}
public IEnumerator<int> GetEnumerator()
{
while (true)
{
yield return _rnd.Next(_minValue, _maxValue + 1);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<int>)this).GetEnumerator();
}
public int Min()
{
return _minValue;
}
}
/// <summary>
/// Combines two generators through addition
/// </summary>
internal class AdditionGenerator : IGenerator<int>
{
private IGenerator<int> _gen1;
private IGenerator<int> _gen2;
public AdditionGenerator(Program.RandomGenerator gen1, Program.IGenerator<int> gen2)
{
this._gen1 = gen1;
this._gen2 = gen2;
}
public IEnumerator<int> GetEnumerator()
{
var en1 = _gen1.GetEnumerator();
var en2 = _gen2.GetEnumerator();
while (true)
{
var hasValue = en1.MoveNext();
if (hasValue != en2.MoveNext())
{
throw new InvalidOperationException("One generator stopped providing values before the other");
}
if (!hasValue)
{
yield break;
}
yield return en1.Current + en2.Current;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<int>)this).GetEnumerator();
}
public int Min()
{
return _gen1.Min() + _gen2.Min();
}
}
}
Conclusion (so far)
I am going to think about this some more. It has a lot of potential as type abstraction, but to be honest, I deal very little in numerical values and math and statistics, so I don't see what I personally could do with this. I suspect, though, that other people might find it very useful or at least interesting. And yes, I am aware of mathematical concepts like interval arithmetic and I am sure there are a ton of existing libraries that already do something like that and much more, but I am looking at this more from the standpoint of computer science and quasi-primitive types than from a mathematical or numerical perspective. If you have any suggestions or ideas or requests, let me know!
Comments
Be the first to post a comment