Search code examples
rascal

How to get all keys from a Rascal map?


Suppose I have a map like so:

map[str,int] a = ("apple": 1, "pear": 2, "banana": 3, "kiwi": 4); 

Is there any way to return all the keys in the map, i.e. "apple", "pear", "banana", "kiwi"? From the documentation at http://tutor.rascal-mpl.org/Rascal/Expressions/Values/Map/Comprehension/Comprehension.html#/Rascal/Expressions/Values/Map/Map.html , it does not seem like there's a built in way. Is it possible?


Solution

  • A number of ways:

    First is just projecting out the first column:

    rascal>map[str,int] a = ("apple": 1, "pear": 2, "banana": 3, "kiwi": 4); 
    map[str, int]: ("banana":3,"pear":2,"kiwi":4,"apple":1)
    rascal>a<0>
    set[str]: {"banana","pear","kiwi","apple"} 
    

    Second is labeling the columns, and doing the same (either the <> notation or the . notation)

    rascal>map[str fruit, int count] b = ("apple": 1, "pear": 2, "banana": 3, "kiwi": 4); 
    map[str fruit, int count]: ("banana":3,"pear":2,"kiwi":4,"apple":1)
    rascal>b<fruit>
    set[str]: {"banana","pear","kiwi","apple"}
    rascal>b.fruit
    set[str]: {"banana","pear","kiwi","apple"}
    

    Finally maps are also generators for their own keys, as in:

    rascal>[ f | f <- a]
    list[str]: ["banana","pear","kiwi","apple"]
    rascal>{ f | f <- a}
    set[str]: {"banana","pear","kiwi","apple"}
    rascal>import IO;
    rascal>for (f <- a)
    >>>>>>>  println(f);
    banana
    pear
    kiwi
    apple