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
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.
Sign up to join this communityI found an article on the subject here.
Essentially you can utilize the yield keyword to programmatically create the next element of your list.
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;
}
The type that most closely corresponds to a lazy Haskell-like list, is IEnumerable<out T>
.
yield
keyword in C#, most collection types can be thought to be able to return an infinite list (depending on actual implementation, of course).IEnumerable<T>
works perfectly fine for infinite sequences.ICollection<T>
has aCount
property which makes no sense for infinite sequences, so implementingICollection<T>
andIList<T>
are rather dubious for infinite collections.