I want to find Haskell’s analogue of infinite list in c# language. I want to use any possible interfaces for such list, like these:
IEnumerable
ICollection
IList
8
I found an article on the subject here.
Essentially you can utilize the yield keyword to programmatically create the next element of your list.
2
Using IEnumerable
and yield return
you can easily create infinite sets.
static IEnumerable<uint> UpDown(uint min = uint.MinValue, uint max = uint.MaxValue, uint step = 1)
{
if (min > max)
throw new ArgumentOutOfRangeException("min", "'min' must be less than or equal to 'max'");
var current = min;
var last = current;
var up = true;
while (true)
{
yield return current;
current += (uint)(up ? step : -step);
if (up && (current >= max || current < last))
{
up = !up;
current = max;
}
else if (!up && (current <= min || current > last))
{
up = !up;
current = min;
}
last = current;
}
}
static IEnumerable<int> Random()
{
while (true)
yield return 4;
}
2
The type that most closely corresponds to a lazy Haskell-like list, is IEnumerable<out T>
.
2