DCSIMG
RE:yield - life = code + sleep

life = code + sleep

RE:yield

Replying to this post about the use of yield, here is an everyday practical example: split a string to lines of text (by newline).

(I do like comparisons, so here’s the Python version too):

C#(xUnit)

   1: static IEnumerable<string> SplitLines(string input)
   2: {
   3:     while (true)
   4:     {
   5:         int idx = input.IndexOf(Environment.NewLine); 
   6:  
   7:         if (idx < 0)
   8:         {
   9:             yield return input;
  10:             break;
  11:         } 
  12:  
  13:         yield return input.Substring(0, idx);
  14:         input = input.Substring(idx + Environment.NewLine.Length);
  15:     }
  16: }

Python

   1: def split(str):
   2:     while True:
   3:         idx = str.find('\n');
   4:         if(idx < 0):
   5:             yield str
   6:             break
   7:         
   8:         yield str[0:idx]
   9:         str = str[idx+1 :]

Sorry, Ruby’s idiom of yielding is a bit twisted. It will not create a generator.

פורסם: Jun 06 2008, 08:36 PM by dotan | with no comments
שלח תגובה

(שדה חובה)  

(שדה חובה)  

(אופציונלי)

(שדה חובה) 

Please add 5 and 1 and type the answer here:


Enter the numbers above: