Pike multiset

Published 3 May, 2007 in Programming - 0 Comments

It’s fascinating: I’ve been using Pike for little over two years now and I have never really understood the Pike data type “multiset”. A multiset is the keys in an associative array – or mapping as they are called in Pike, or hash in Perl, or HashTable in C# – with the values left out. So if you have a Pike mapping that looks like ([ "key1" : 1, "key2" : 2, "key3" : 3 ]) a multiset of that would look like ([ "key1" : 1, "key2" : 2, "key3" : 3 ]) and an array would be ([ "key1" : 1, "key2" : 2, "key3" : 3 ]). Mappings and arrays I have used a lot, of course, but it was quite recently it came to me what the multiset is good for!

Lets say you have a function that takes a string as argument and that argument can have like 12 different values but you only want some action to take place if the value is one of three out of the twelve possibilities. In many languages that could be written like this Pike example:

7 lines of Pike
  1. string my_function(string arg)
  2. {
  3. if (arg != “a_value” && arg != “b_value” && arg != “g_value”)
  4. return “no”;
  5. return “yes”;
  6. }

I don’t know how many times I’ve written code like that. But here the Pike multiset really shines. This is how you could use the multiset:

7 lines of Pike
  1. string my_function(string arg)
  2. {
  3. if (!(< “a_value”, “b_value”, “g_value” >)[arg])
  4. return “no”;
  5. return “yes”;
  6. }

I think that’s pretty nice. And that’s probably not the only thing the multiset is useful for.

While I’m at it, what about these nice syntactic sugar flakes of Pike:

3 lines of Pike
  1. string str = “one two three four five six”;
  2. array a_str = str/” “;
  3. str = a_str*“, “;

The same in PHP

3 lines of PHP
  1. $str = “one two three four five six”;
  2. $a_str = explode(” “, $str);
  3. $str = implode(“, “, $a_str);

Even though I’ve used PHP for 7-8 years I still have trouble remembering in what order the arguments is supposed to come in the function call. ;)