Version 2 (modified by hopscc, 12 years ago) |
---|
Pair
A Pair is a simple generic class holding 2 typed values.
It is similar to a (2 element) Tuple but less complete.
This class is now part of the Cobra Runtime Library.
There are two forms - one for both elements the same Type and another for separate element types
oneType = Pair<of String>('one', 'two') twoType = Pair<of String, int>('one', 2)
The elements of the pair are accessed as .a and .b or via indexes as [0] and [1].
A Pair is enumerable so you can also use a for loop on it or unpack the pair
elements using multivariable assignment.
p = Pair<of int, String>(1, 'Chook') assert p.a == 1 and p.b == 'Chook' assert p[0] == 1 and p[1] == 'Chook' assert p.toString == "Pair(1, 'Chook')" for o in p # o is GCD of elements - object print o n,val = p assert n == 1 #int assert val =='Chook' #String p2 = Pair<of int>(1,2) for i in p2 # i is int print i+100 #101 and 102
Comparisons between Pairs such as p1 < p2 are effectively comparisons of their elements.
You can use a Pair's hash code as long as you don't modify the Pair or its elements. That means you can put pairs in sets or use them as keys in dictionaries.
Discussion - http://cobra-language.com/forums/viewtopic.php?f=4&t=484
Source - Pair.cobra