Search code examples
hhvmhacklang

Hack iterate (map) over Map


I have a Map such as:

$m = Map {
  'sort' => 'created',
  'order' => 'desc',
}

I want to turn that into a string:

'sort:created order:desc'

I can do this with arrays as explained in this SO answer:

implode(' ', array_map(($k, $v) ==> $k.':'.$v, array_keys($m), $m))

I've read the documentation of Map::items and tried:

$m->items()->map(($key, $value) ==> print($key))

But this prints nothing.

I'm looking for a oneliner like with the arrays, no loops.


Solution

  • map()'s parameter is a function that only takes one argument; if you run the typechecker, it will tell you this:

    test.php:9:20,20: Invalid argument (Typing[4039])
      /tmp/hh_server/hhi_1ebd4af3/hhi/interfaces.hhi:363:27,44: Number of  arguments doesn't match
      test.php:9:20,20: Because of this definition
    

    What you want is mapWithKey() https://3v4l.org/GF69D:

    $m->mapWithKey(($key, $value) ==> print($key));
    

    You can also use exactly the same code you were using for arrays: https://3v4l.org/mSREI