| 1 | = Pair = |
| 2 | |
| 3 | A Pair is a simple generic class holding 2 typed values. |
| 4 | |
| 5 | It is similar to a (2 element) Tuple but less complete. |
| 6 | |
| 7 | This class is now part of the Cobra Runtime Library. |
| 8 | |
| 9 | |
| 10 | There are two forms - one for both elements the same Type and another for separate element types |
| 11 | {{{ |
| 12 | #!cobra |
| 13 | oneType = Pair<of String>('one', 'two') |
| 14 | twoType = Pair<of String, int>('one', 2) |
| 15 | }}} |
| 16 | |
| 17 | The elements of the pair are accessed as .a and .b or via indexes as ![0] and ![1].[[BR]] |
| 18 | A Pair is enumerable so you can also use a `for` loop on it or unpack the pair |
| 19 | elements using multivariable assignment. |
| 20 | {{{ |
| 21 | #!cobra |
| 22 | p = Pair<of int, String>(1, 'Chook') |
| 23 | assert p.a == 1 and p.b == 'Chook' |
| 24 | assert p[0] == 1 and p[1] == 'Chook' |
| 25 | assert p.toString == "Pair(1, 'Chook')" |
| 26 | |
| 27 | for o in p # o is GCD of elements - object |
| 28 | print o |
| 29 | |
| 30 | n,val = p |
| 31 | assert n == 1 #int |
| 32 | assert val =='Chook' #String |
| 33 | |
| 34 | p2 = Pair<of int>(1,2) |
| 35 | for i in p2 # i is int |
| 36 | print i+100 #101 and 102 |
| 37 | |
| 38 | }}} |
| 39 | |
| 40 | |
| 41 | Comparisons between Pairs such as `p1 < p2` are effectively comparisons |
| 42 | of their elements. |
| 43 | |
| 44 | You can use a Pair's hash code as long as you don't modify the Pair or its elements. |
| 45 | That means you can put pairs in sets or use them as keys in dictionaries. |
| 46 | |
| 47 | |
| 48 | |