Wiki

Changes between Initial Version and Version 1 of ForExpression

Show
Ignore:
Timestamp:
12/20/10 01:36:40 (14 years ago)
Author:
todd.a
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • ForExpression

    v1 v1  
     1The '''for''' expression enables looping in expressions and results in a list with the results. 
     2 
     3{{{ 
     4for <var> in <ienumerable> [where <condition>] get <expr> 
     5for <var> in <ienumerable> where <condition> 
     6}}} 
     7 
     8The '''var''' may be declared in the expression or it can be a preexisting variable. The '''ienumerable''' is any expression that implements the '''IEnumerable''' interface. The '''condition''' is optional and is used to filter the list. Finally, the expr is evaluated for each individual item resulting in the elements of the final list. 
     9 
     10The '''get <expr>''' part can be excluded in the presence of '''where''' in which case it is assumed to be '''get <var>'''. 
     11 
     12Both '''ienumerable''' and the resulting list may be empty. 
     13 
     14The resulting list is always newly created. The type of the list is '''List<of T>''' where T is the type of '''expr'''. There is no requirement that the type of expr be the same as the type of what the '''ienumerable''' contains. 
     15 
     16If the '''for''' expression is part of a more complex expression—especially if it is the beginning of one—then put parenthesis around it to prevent the get <expr> portion of the grammar from consuming the rest of the complex expression. See below for an example. 
     17 
     18There is also a statement version of the for loop. 
     19 
     20{{{ 
     21#!cobra 
     22# Example 1 t = for x in [1, 2, 3] get x*x  
     23# type of `x` is int, type of `t` is List<of int> 
     24assert t.count==3  
     25assert t[0]==1  
     26assert t[1]==4  
     27assert t[2]==9  
     28 
     29# Example 2: Explicit variable typing  
     30names = for name as String in provider.names get name.toLower  
     31 
     32# Example 3: Grouping with parens  
     33assert (for s in ['aa', 'bbbb', 'cccccc'] get s.length) == [2, 4, 6]  
     34# not needed in this case:  
     35assert [2, 4, 6] == for s in ['aa', 'bbbb', 'cccccc'] get s.length  
     36 
     37# Example 3: with `where`  
     38names = for name in names where name.trim.length get name.trim  
     39 
     40# Example 4: `get x` is implied  
     41t = for x in numbers where x > 0  
     42}}}