What would the MSDN sample look like without the yield keyword? You may use any example if you perfer. I would just like to understand what is going on under the hood.
Is the yield operator eagerly or lazily evaluated?
Sample:
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach (int i in Power(2, 8))
{
Console.Write("{0} ", i);
}
}
}
MSDN - Yield Keyword
If the yield operator is eagerly evaluated here is my guess:
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
List<int> powers;
while (counter++ < exponent)
{
result = result * number;
powers.add(result);
}
return powers;
}
I have no clue what it might look like if the yield operator is lazily evaluated.
Update: Reflector gives this:
public class List
{
// Methods
public List();
private static void Main();
public static IEnumerable Power(int number, int exponent);
// Nested Types
[CompilerGenerated]
private sealed class <Power>d__0 : IEnumerable<object>, IEnumerable, IEnumerator<object>, IEnumerator, IDisposable
{
// Fields
private int <>1__state;
private object <>2__current;
public int <>3__exponent;
public int <>3__number;
private int <>l__initialThreadId;
public int <counter>5__1;
public int <result>5__2;
public int exponent;
public int number;
// Methods
[DebuggerHidden]
public <Power>d__0(int <>1__state);
private bool MoveNext();
[DebuggerHidden]
IEnumerator<object> IEnumerable<object>.GetEnumerator();
[DebuggerHidden]
IEnumerator IEnumerable.GetEnumerator();
[DebuggerHidden]
void IEnumerator.Reset();
void IDisposable.Dispose();
// Properties
object IEnumerator<object>.Current { [DebuggerHidden] get; }
object IEnumerator.Current { [DebuggerHidden] get; }
}
}
IEnumerator<object> IEnumerable<object>.GetEnumerator()
{
List.<Power>d__0 d__;
if ((Thread.CurrentThread.ManagedThreadId == this.<>l__initialThreadId) && (this.<>1__state == -2))
{
this.<>1__state = 0;
d__ = this;
}
else
{
d__ = new List.<Power>d__0(0);
}
d__.number = this.<>3__number;
d__.exponent = this.<>3__exponent;
return d__;
}
private bool MoveNext()
{
switch (this.<>1__state)
{
case 0:
this.<>1__state = -1;
this.<counter>5__1 = 0;
this.<result>5__2 = 1;
while (this.<counter>5__1++ < this.exponent)
{
this.<result>5__2 *= this.number;
this.<>2__current = this.<result>5__2;
this.<>1__state = 1;
return true;
Label_0065:
this.<>1__state = -1;
}
break;
case 1:
goto Label_0065;
}
return false;
}
First off, yield is not an operator. yield return and yield break are statements.
There are plenty of articles available on how the compiler implements iterator blocks. Start by reading the C# specification section on iterator blocks; it gives some suggestions for how an implementer of C# might want to go about it.
Next read Raymond Chen's series "The implementation of iterators in C# and its consequences"
http://www.bing.com/search?q=raymond+chen+the+implementation+of+iterators
Next, read Jon Skeet's book chapter on the subject:
http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx
If after all that you are still interested then read my series on the design factors that went into this feature:
http://blogs.msdn.com/b/ericlippert/archive/tags/iterators/
Back in the good old days, before we had the yield operator, we used to write classes which implemented IEnumerator.
class PowerEnumerator : IEnumerator<int>
{
private int _number;
private int _exponent;
private int _current = 1;
public PowerEnumerator(int number, int exponent)
{
_number = number;
_exponent = exponent;
}
public bool MoveNext()
{
_current *= number;
return _exponent-- > 0;
}
public int Current
{
get
{
if (_exponent < 0) throw new InvalidOperationException();
return _current;
}
}
}
Or something like that. It wasn't fun, let me tell you.
Let .NET Reflector decompile it. It's a generic solution (a state machine actually), but quite complex, > 20 lines of codes if I remember correctly.
Lazy. That's the point why yield can be quite efficient.
It would be a custom implementation of IEnumerable<T>, not leaning on an existing implementation such as List<T>
Lazily.
More info available here.
Related
I'm trying to do a Radix sort in a Linked list class. I found radix sort algorithm for array and am trying to change it to work with my linked list. However, I'm a bit struggling. The code I'm trying to change is taken from http://www.w3resource.com/csharp-exercises/searching-and-sorting-algorithm/searching-and-sorting-algorithm-exercise-10.php I tested the code with an array and it worked. Does anybody have any ideas how to make radix sort work in a linked list?
//abstract class
abstract class DataList
{
protected int length;
public int Length { get { return length; } }
public abstract double Head();
public abstract double Next();
public abstract void Swap(int a, int b);
public void Print(int n)
{
Console.Write("{0} ", Head());
for (int i = 1; i < n; i++)
Console.Write("{0} ", Next());
Console.WriteLine();
}
}
//linked list class
class LinkedList : DataList
{
class MyLinkedListNode
{
public MyLinkedListNode nextNode { get; set; }
public int data { get; set; }
public MyLinkedListNode(int data)
{
this.data = data;
}
public MyLinkedListNode()
{
this.data = 0;
}
}
MyLinkedListNode headNode;
MyLinkedListNode prevNode;
MyLinkedListNode currentNode;
public LinkedList(int n, int min, int max)
{
length = n;
Random rand = new Random();
headNode = new MyLinkedListNode(rand.Next(min, max));
currentNode = headNode;
for (int i = 1; i < length; i++)
{
prevNode = currentNode;
currentNode.nextNode = new MyLinkedListNode(rand.Next(min, max));
currentNode = currentNode.nextNode;
}
currentNode.nextNode = null;
}
public LinkedList()
{
headNode = new MyLinkedListNode();
currentNode = headNode;
}
public override double Head()
{
currentNode = headNode;
prevNode = null;
return currentNode.data;
}
public override double Next()
{
prevNode = currentNode;
currentNode = currentNode.nextNode;
return currentNode.data;
}
public override void Swap(int a, int b)
{
prevNode.data = a;
currentNode.data = b;
}
//my radix sort
public void radixSort()
{
int j = 0;
LinkedList tmp = new LinkedList();
for (int shift = 31; shift > -1; --shift)
{
//I try to go trough old list
MyLinkedListNode current = headNode;
while (current != null)
{
bool move = (current.data << shift) >= 0;
//I found this expression somewhere and I'm trying to use it to form a new Linked list (tmp)
if (shift == 0 ? !move : move)
;
else
{
if (tmp.headNode == null)
tmp.headNode = currentNode;
else
{
tmp.currentNode.nextNode = current;
//infinite loop happens on the commented line
//tmp.currentNode = tmp.currentNode.nextNode;
j++;
}
current = current.nextNode;
}
}
}
}
Following the C# radix sort example, you need an array of ten lists. Move nodes from the original list into the ten lists, appending a node with least signfificant digit == '0' into array_of_lists[0], '1' into array_of_list[1], and so on. After the original list is emptied, then concatenate the array of lists back into the original list and repeat for the next to least significant digit. Repeat the process until all the digits are handled.
You could use a larger base, such as base 16, where you would use an array of 16 lists. You can then select each "digit" using a shift and an and .
I have a generic type called Vector<T>, I created it as so, cause the T might be float or Complex :
public class Vector<T>
{
#region Properties
public ulong Length
{
get
{
return _length;
}
}
public VectorType VectorType
{
get
{
return _vectorType;
}
}
#endregion
#region Indexers
public T this[ulong index]
{
get
{
return _data[index];
}
set
{
_data[index] = value;
}
}
#endregion
#region Constructors
public Vector(VectorType vectorType, T[] data)
{
if (!((data is float[]) || (data is Complex[])))
{
throw new InvalidDataException("Data must be array of float or array of Complex");
}
_data = new T[_length = (ulong)data.Length];
for (ulong i = 0; i < _length; i++)
{
_data[i] = data[i];
}
_vectorType = vectorType;
}
public Vector(VectorType vectorType, Vector<T> vector)
{
_data = new T[_length = vector.Length];
for (ulong i = 0; i < _length; i++)
{
_data[i] = vector[i];
}
_vectorType = vectorType;
}
#endregion
#region Methods
//Unity Matrix, this vector has 1/N everywhere
public static Vector<float> e(VectorType vectorType, ulong length)
{
var data = new float[length];
for (ulong i = 0; i < length; i++)
{
data[i] = (float)1 / length;
}
var vectorE = new Vector<float>(vectorType, data);
return vectorE;
}
public float Sum()
{
float sum = 0;
if (_data is float[])
{
sum = (_data as float[]).Sum();
}
else
{
if (_data is Complex[])
{
for (ulong i = 0; i < _length; i++)
{
sum += (float)
Math.Sqrt(Math.Pow((_data[i] as Complex?).Value.Real, 2) +
Math.Pow((_data[i] as Complex?).Value.Imaginary, 2));
}
}
}
return sum;
}
public bool CheckIfSochasitc()
{
return Math.Abs(Sum() - 1) < float.Epsilon;
}
public void Normalize()
{
var sum = Sum();
if (_data is float[])
{
for (ulong i = 0; i < _length; i++)
{
float x = ((float) _data[i])/sum;
_data[i] = (T)x;
}
}
}
#endregion
#region Operators
//I omitted the code inhere to avoid overload
#endregion
#region Fields
private ulong _length;
private readonly VectorType _vectorType;
private T[] _data;
#endregion
}
public enum VectorType
{
Row,Column
}
My problem is that I have a generic array (if I can call it so) :
private T[] _data;
And I have the Normalize() method:
public void Normalize()
{
var sum = Sum();
if (_data is float[])
{
for (ulong i = 0; i < _length; i++)
{
//Here is the problem
_data[i] = ((_data[i] as float?) / sum);
}
}
}
This doesn't work saying can't cast float to T tried to search but couldn't find helpful aide, any clarification I'd be thankful.
Update :
The Sum() method always returns a float
It's not clear why you're converting to float? at all (or why you're using ulong as the index variable type...) but you just need to cast the result back to T - otherwise you can't assign it back into an array of type T[]. Additionally, you need to cast to object (in order to convert back to T:
float x = ((float) (object) data[i]) / sum;
data[i] = (T) (object) x;
You can use float? for the first line, with as, to avoid boxing - but then you need to get the non-nullable value:
float x = (data[i] as float?).Value / sum;
Both are pretty ugly :(
As noted in comments though, this sort of thing is usually an indication of the design not really being properly generic at all. We don't know what type Sum() returns, but you should consider just how "general" your type is to start with.
May be you can try this
if (typeof(_data) == float[])
{
for (ulong i = 0; i < _length; i++)
{
_data[i] = ((_data[i] as float?) / sum);
}
}
I'm trying to compare an object with an int value such as
if (myObject - 5 == 0)
doSomething();
my class could look something like this: (most setters/getters removed, so don't mind that all variables are private)
public class SomeClass
{
public string name;
private int minValue;
private int maxValue;
private int currValue;
public int getCurrentValue()
{
return currValue;
}
}
What I'm trying to achieve is something like this:
someClassInstance - 5;
to be equal
someClassInstance.getCurrentValue() - 5;
Can I make an override for the object to act as an int (it's own variable) opposed to just being an object?
May be operator is the case?
public class SomeClass {
...
public static int operator -(SomeClass left, int right) {
if (Object.ReferenceEquals(null, left))
throw new ArgumentNullException("left");
return left.getCurrentValue() - right;
}
}
...
SomeClass someClassInstance = new SomeClass(...);
int result = someClassInstance - 5;
Another possibility (based on implicit operator) is to convert SomeClass implicitly to int whenever required:
public class SomeClass {
...
// Whenever int is requiered, but SomeClass exists make a conversion
public static implicit operator int(SomeClass value) {
if (Object.ReferenceEquals(null, value))
throw new ArgumentNullException("value");
return value.getCurrentValue();
}
}
...
SomeClass someClassInstance = new SomeClass(...);
int result = someClassInstance - 5;
Actually you would be much better off overriding operator int, that way you can do far more calculations with less overloads:
using System;
namespace Demo
{
public class SomeClass
{
public string name;
private int minValue;
private int maxValue;
public int currValue;
public int getCurrentValue()
{
return currValue;
}
public static implicit operator int(SomeClass value)
{
if (value == null)
throw new ArgumentNullException("value");
return value.currValue;
}
}
internal class Program
{
private void run()
{
var test = new SomeClass {currValue = 5};
if (test - 5 == 0)
Console.WriteLine("It worked");
if (test + 5 == 10)
Console.WriteLine("This also worked");
}
private static void Main()
{
new Program().run();
}
}
}
You could experiment with a mixture of implicit conversions and operator overloading, but from my experience you will never make it work as seamlessly as you wish (and as you could get it to work in C++).
If I were you, I would change the getCurrentValue to a property:
public int CurrentValue
{
get {return currValue};
}
and just use someClassInstance.CurrentValue -5
To clarify I'm doing this in Unity3D, which may or may not be important?
I'm trying to figure out if I can pass a value by ref to an IEnumerator function that does not yield. If I try to do it with one that yields, VS2010 complains ("Iterators cannot have ref or out parameters"), but, if I wrap the call up with a similar IEnumerator function that calls the yielding function, but does not yield itself, the error goes away and things appear to work. I'm trying to find out if I'm in unexpected behavior land or if this is normal behavior.
Here's an example of what I'm doing:
IEnumerator Wrapper(ref int value)
{
int tmp = ++value; // This is the ONLY place I want the value
return Foo(tmp); // of the ref parameter to change!
} // I do _NOT_ want the value of the ref
// parameter to change in Foo()!
IENumerator Foo(int value)
{
// blah blah
someFunc(value);
someSlowFunc();
yield return null;
yield return null;
}
Looks good. The top function just returns an IEnumerator - but is otherwise a normal function. The bottom function is an IEnumerator [transformed into a funky class by the compiler] and as such cannot have a ref value.
The top function could have been written as such:
void Wrapper(ref int value, out IEnumerator coroutine)
{
int tmp = ++value;
coroutine = Foo(tmp);
}
This is a little more messy - but it shows how this is a normal function that deals with two pieces of data. A int passed by referance, and a IEnumerator [just a class] that it returns [in this example by using out].
Supplemental: This is how stuff works behind the scenes:
static void Main(string[] args)
{
//Lets get the 'IEnumerable Class' that RandomNum gets compiled down into.
var IEnumeratorClass = RandomNum(10, 10);
//All an IEnumerable is is a class with 'GetEnumerator'... so lets get it!
var IEnumerableClass = IEnumeratorClass.GetEnumerator();
//It can be used like so:
while (IEnumerableClass.MoveNext())
{
Console.WriteLine(IEnumerableClass.Current);
}
Console.WriteLine(new String('-', 10));
//Of course, that's a lot of code for a simple job.
//Luckily - there's some nice built in functionality to make use of this.
//This is the same as above, but much shorter
foreach (var random in RandomNum(10, 10)) Console.WriteLine(random);
Console.WriteLine(new String('-', 10));
//These simple concepts are behind Unity3D coroutines, and Linq [which uses chaining extensively]
Enumerable.Range(0, 100).Where(x => x % 2 == 0).Take(5).ToList().ForEach(Console.WriteLine);
Console.ReadLine();
}
static Random rnd = new Random();
static IEnumerable<int> RandomNum(int max, int count)
{
for (int i = 0; i < count; i++) yield return rnd.Next(i);
}
//This is an example of what the compiler generates for RandomNum, see how boring it is?
public class RandomNumIEnumerableCompiled : IEnumerable<int>
{
int max, count;
Random _rnd;
public RandomNumIEnumerableCompiled(int max, int count)
{
this.max = max;
this.count = count;
_rnd = rnd;
}
IEnumerator IEnumerable.GetEnumerator()
{
return new RandomNumIEnumeratorCompiled(max, count, rnd);
}
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
return new RandomNumIEnumeratorCompiled(max, count, rnd);
}
}
public class RandomNumIEnumeratorCompiled : IEnumerator<int>
{
int max, count;
Random _rnd;
int current;
int currentCount = 0;
public RandomNumIEnumeratorCompiled(int max, int count, Random rnd)
{
this.max = max;
this.count = count;
_rnd = rnd;
}
int IEnumerator<int>.Current { get { return current; } }
object IEnumerator.Current { get { return current; } }
public bool MoveNext()
{
if (currentCount < count)
{
currentCount++;
current = rnd.Next(max);
return true;
}
return false;
}
public void Reset() { currentCount = 0; }
public void Dispose() { }
}
Background
I'm working on a symmetric rounding class and I find that I'm stuck with regards to how to best find the number at position x that I will be rounding. I'm sure there is an efficient mathematical way to find the single digit and return it without having to resort to string parsing.
Problem
Suppose, I have the following (C#) psuedo-code:
var position = 3;
var value = 102.43587m;
// I want this no ↑ (that is 5)
protected static int FindNDigit(decimal value, int position)
{
// This snippet is what I am searching for
}
Also, it is worth noting that if my value is a whole number, I will need to return a zero for the result of FindNDigit.
Does anyone have any hints on how I should approach this problem? Is this something that is blaringly obvious that I'm missing?
(int)(value * Math.Pow(10, position)) % 10
How about:
(int)(double(value) * Math.Pow(10, position)) % 10
Basically you multiply by 10 ^ pos in order to move that digit to the one's place, and then you use the modulus operator % to divide out the rest of the number.
using System;
public static class DecimalExtensions
{
public static int DigitAtPosition(this decimal number, int position)
{
if (position <= 0)
{
throw new ArgumentException("Position must be positive.");
}
if (number < 0)
{
number = Math.Abs(number);
}
number -= Math.Floor(number);
if (number == 0)
{
return 0;
}
if (position == 1)
{
return (int)(number * 10);
}
return (number * 10).DigitAtPosition(position - 1);
}
}
Edit:
If you wish, you may separate the recursive call from the initial call, to remove the initial conditional checks during recursion:
using System;
public static class DecimalExtensions
{
public static int DigitAtPosition(this decimal number, int position)
{
if (position <= 0)
{
throw new ArgumentException("Position must be positive.");
}
if (number < 0)
{
number = Math.Abs(number);
}
return number.digitAtPosition(position);
}
static int digitAtPosition(this decimal sanitizedNumber, int validPosition)
{
sanitizedNumber -= Math.Floor(sanitizedNumber);
if (sanitizedNumber == 0)
{
return 0;
}
if (validPosition == 1)
{
return (int)(sanitizedNumber * 10);
}
return (sanitizedNumber * 10).digitAtPosition(validPosition - 1);
}
Here's a few tests:
using System;
using Xunit;
public class DecimalExtensionsTests
{
// digit positions
// 1234567890123456789012345678
const decimal number = .3216879846541681986310378765m;
[Fact]
public void Throws_ArgumentException_if_position_is_zero()
{
Assert.Throws<ArgumentException>(() => number.DigitAtPosition(0));
}
[Fact]
public void Throws_ArgumentException_if_position_is_negative()
{
Assert.Throws<ArgumentException>(() => number.DigitAtPosition(-5));
}
[Fact]
public void Works_for_1st_digit()
{
Assert.Equal(3, number.DigitAtPosition(1));
}
[Fact]
public void Works_for_28th_digit()
{
Assert.Equal(5, number.DigitAtPosition(28));
}
[Fact]
public void Works_for_negative_decimals()
{
const decimal negativeNumber = -number;
Assert.Equal(5, negativeNumber.DigitAtPosition(28));
}
[Fact]
public void Returns_zero_for_whole_numbers()
{
const decimal wholeNumber = decimal.MaxValue;
Assert.Equal(0, wholeNumber.DigitAtPosition(1));
}
[Fact]
public void Returns_zero_if_position_is_greater_than_the_number_of_decimal_digits()
{
Assert.Equal(0, number.DigitAtPosition(29));
}
[Fact]
public void Does_not_throw_if_number_is_max_decimal_value()
{
Assert.DoesNotThrow(() => decimal.MaxValue.DigitAtPosition(1));
}
[Fact]
public void Does_not_throw_if_number_is_min_decimal_value()
{
Assert.DoesNotThrow(() => decimal.MinValue.DigitAtPosition(1));
}
[Fact]
public void Does_not_throw_if_position_is_max_integer_value()
{
Assert.DoesNotThrow(() => number.DigitAtPosition(int.MaxValue));
}
}
Edited: Totally had the wrong and opposite answer here. I was calculating the position to the left of the decimal instead of the right. See the upvoted answers for the correct code.
I found this one here working:
public int ValueAtPosition(int value, int position)
{
var result = value / (int)Math.Pow(10, position);
result = result % 10;
return result;
}
And also this one to know the full value (i.e.: 111, position 3 = 100 , sorry I don't know the proper name):
public int FullValueAtPosition(int value, int position)
{
return this.ValueAtPosition(value, position) * (int)Math.Pow(10, position);
}
How about this:
protected static int FindNDigit(decimal value, int position)
{
var index = value.ToString().IndexOf(".");
position = position + index;
return (int)Char.GetNumericValue(value.ToString(), position);
}
None of the previous solutions worked for me, so here is a working one :
var result = value / Math.Pow(10, Math.Truncate((Math.Log10(value) + 1) - position));
return (int)(result % 10);