Directly yield other IEnumerable #6463
Answered
by
HaloFour
lucasteles
asked this question in
Language Ideas
-
Today if we have a yieldable IEnumerable function that needs to consume and return values from another IEnumerable we need to explicitly enumerate it and return: using System;
using System.Linq;
using System.Collections.Generic;
IEnumerable<int> RandomInt(int qtd)
{
for(var i = 0; i<=qtd; i++)
yield return Random.Shared.Next(qtd);
}
IEnumerable<int> Values(int qtd)
{
foreach(var n in Enumerable.Range(0, qtd))
yield return n;
foreach(var n in RandomInt(qtd))
yield return n;
}
Console.WriteLine(string.Join(",",Values(5))); My proposal idea is a syntax to make this simpler, inspired by how F# deals with the same problem: open System.Linq
open System
let randomInt max = seq {
for i = 0 to max do
yield System.Random.Shared.Next max
}
// explicitly enumerate
let valuesExplit max = seq {
for i in Enumerable.Range(0, max) do
yield i
for i in randomInt(max) do
yield i
}
// auto unwrap
let values max = seq {
// note the "!"
yield! Enumerable.Range(0, max)
yield! randomInt(max)
}
Console.WriteLine(String.Join(",", valuesExplit(5)));
Console.WriteLine(String.Join(",", values(5))); The "!" is what makes the yield automatically enumerate and return from other enumerable. This syntax is not csharp-ish, so I thought of something like: IEnumerable<int> RandomInt(int qtd)
{
for(var i = 0; i<=qtd; i++)
yield return Random.Shared.Next(qtd);
}
IEnumerable<int> Values(int qtd)
{
yield Enumerable.Range(0, qtd);
yield RandomInt(qtd);
} This could make yieldable and LINQ to clue seamless and is a nice syntax sugar |
Beta Was this translation helpful? Give feedback.
Answered by
HaloFour
Sep 16, 2022
Replies: 1 comment 1 reply
-
See also: |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
svick
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also:
#378
#5303