Discussion:
How do you understand this task
(too old to reply)
Tony Johansson
2016-05-04 09:44:13 UTC
Permalink
Hello!

I have this task from a book and I'm a little bit unsure how to understand
it. It's quite vague.
[Demonstrate how to use iterator blocks to implement a function that takes a
sequence of integers as input, doubles each element and generates a new
sequence of doubled elements.]

Would you consider my solution to satisfy the task.


public class Example
{
static void Main()
{
List<int> result = new List<int>();

int[] ints = { 1, 2, 3, 4, 5 };
foreach (int number in DoubleEach(ints))
{
result.Add(number);
}
}

public static System.Collections.Generic.IEnumerable<int>
DoubleEach(IEnumerable<int> ints)
{
foreach(int tal in ints)
{
yield return tal*2;
}
}
}

//Tony
Stefan Ram
2016-05-04 22:29:16 UTC
Permalink
Post by Tony Johansson
[Demonstrate how to use iterator blocks to implement a function that takes a
sequence of integers as input, doubles each element and generates a new
sequence of doubled elements.]
Since no one else has replied so far:

It looks like an iterator block to me, and if it compiles and
the result then is »{ 2, 4, 6, 8, 10 }«, it looks correct to me,
but I have not yet really studied »IEnumerable« or »yield« in C#.
Arne Vajhøj
2016-05-04 23:17:06 UTC
Permalink
Post by Tony Johansson
I have this task from a book and I'm a little bit unsure how to
understand it. It's quite vague.
[Demonstrate how to use iterator blocks to implement a function that
takes a sequence of integers as input, doubles each element and
generates a new sequence of doubled elements.]
Would you consider my solution to satisfy the task.
public class Example
{
static void Main()
{
List<int> result = new List<int>();
int[] ints = { 1, 2, 3, 4, 5 };
foreach (int number in DoubleEach(ints))
{
result.Add(number);
}
}
public static System.Collections.Generic.IEnumerable<int>
DoubleEach(IEnumerable<int> ints)
{
foreach(int tal in ints)
{
yield return tal*2;
}
}
}
Yes.

Note that again a simpler solution exist:

ints.Select(v => 2*v)

will do the same as the DoubleEach method.

But most likely you are expected to write the DoubleEach method.

Arne

Continue reading on narkive:
Loading...