I would like to define a generic function to extract keys from a map, something like this:
public list[K] keys(map[K,V] aMap) {
return [ key | key:val <- aMap ];
}
Although no syntax error is given, this does not work. Is there a way to do it?
You can define this as
public list[&K] keys(map[&K,&V] aMap) {
return [ k | k <- aMap ];
}
Note that the keys are unordered, so it may make more sense to return them as a set instead of as a list. You can also always get the keys or values out as sets directly by projecting them out of the map, using either
aMap<0>
for the set of keys or
aMap<1>
for the set of values. Finally, the Set module contains a toList function, so you could do this in one line as
toList(aMap<0>)
which will give you the same result as calling the keys function.