程式扎記: [ GroovyGN ] Keep Your Values in Ranges

標籤

2015年9月18日 星期五

[ GroovyGN ] Keep Your Values in Ranges

Source From Here 
Ranges are lists with sequential values. Each range is also a list object, because Range extends java.util.List. A range can be inclusive (so both begin and end values are in the range) or exclusive (the end value is not in the range). We use .. for an inclusive range and ..< for an exclusive range. 

Each object that implements the Comparable interface and implements a next() and previous() method can be used for a range. So this means we can write our own objects so they can be used in ranges, but also we can use for example String objects or Enum values in a range. 
  1. // Simple ranges with number values.  
  2. def ints = 1..10  
  3. assert [12345678910] == ints  
  4. assert 10 == ints.size()  
  5. assert 1  == ints.from  
  6. assert 10 == ints.to  
  7.   
  8. // We can step through the values.  
  9. def list = []  
  10. ints.step(2) { list << it }  
  11. assert [13579] == list  
  12.   
  13. // A range is just a List.  
  14. assert 1  == ints[0]  
  15. assert 10 == ints.last()  
  16. def s = ''  
  17. (2..4).each { s += it }  
  18. assert '234' == s  
  19.   
  20. // Exclusive range.  
  21. def exclusive = 2..<8  
  22. assert [234567] == exclusive  
  23. assert 6 == exclusive.size()  
  24. assert !exclusive.contains(8)  
  25.   
  26. // Object with next() and previous() can be used  
  27. // in ranges. Groovy extends Java enum with   
  28. // next() and previous() so we can use it in ranges.  
  29. enum Compass {  
  30.     NORTH, NORTH_EAST, EAST, SOUTH_EAST,   
  31.     SOUTH, SOUTH_WEST, WEST, NORTH_WEST  
  32. }  
  33. def northToSouth = Compass.NORTH..Compass.SOUTH  
  34. assert 5 == northToSouth.size()  
  35. assert Compass.EAST == northToSouth[2]  
  36. assert northToSouth.contains(Compass.SOUTH_EAST)  
  37.   
  38. // Bonus: next() and previous() are equivalent to   
  39. // ++ and -- operators.  
  40. def region = Compass.SOUTH  
  41. assert Compass.SOUTH_WEST == ++region  
  42. assert Compass.SOUTH == --region  
Supplement 
The collective Groovy datatypes - Working with ranges

沒有留言:

張貼留言

網誌存檔