Pair in Hack

The Hack Language supports various collection types including Pair. There are various simple ways to use Pair in Hack Language in Hack Language Facebook.
Pairs are an indexed-based collection that can store values in exactly in pair of two.
One other interesting fact about pair is that they can store mutable values, But still they not widely used. In most of the cases 'tuples' are preferred more than 'pair' in practical situations.
In Hack Language the 'pair' keyword is used to create pair type collections. While creating an pair we exactly pass a pair of two values. I have described the use of pair in the example shown below:

Using Pair in Hack Language:

<?hh
 function main() {
  $pair1 = Pair {100, 'value'};
  echo $pair1[0] . "\n";
  echo $pair1[1] . "\n";
  echo "\n";
  foreach ($pair1 as $val) {
    echo $val . "\n";
  }
}
main();
Output:
100 
value 
100 
value 
In the above example, I have demonstrated that how we can simply create a pair and the various ways to access the elements from a pair. In the first way, we have accessed the elements of the pair by specifying the exact index of the element i.e key value 0 refers to the first element and the key value 1 refers to the second element and if the user uses any others it simply generates an out of bound exception. While in the second approach, the for-each loop is used to access the elements. I have also demonstrated that the pair collection can store any type of values that means that values might be integers, real numbers, characters, strings , etc. Thus, pair can be accessed by using any of the above approaches as convenient for the user. Hope the above tutorial is helpful for you. For any queries related to the above topic please mention in the comments below.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.