Wiki

Changes between Version 1 and Version 2 of Pair

Show
Ignore:
Timestamp:
01/08/13 02:10:47 (12 years ago)
Author:
hopscc
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • Pair

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