Search code examples
dictionaryrascal

How to cast a value type to Map in Rascal?


I have a variable of type value that stores a map, but I can not access the values by providing the keys:

rascal>a
value: ("s":"s")

rascal>a["s"]
|stdin:///|(2,3,<1,2>,<1,5>): subscript not supported on value at |stdin:///|(2,3,<1,2>,<1,5>)
☞ Advice

How can I parse the value to map in order to be able to retrieve my value ?


Solution

  • if (map[str,str] myMap := a) {
       // do stuff with myMap
    }
    else {
      throw "<a> is not a map?";
    }
    

    Another way of "narrowing types" is using pattern matching in function parameters:

    rascal>value x = 1;
    int: 1
    rascal>int myFunc(int i) = 2 * i;
    ok
    rascal>myFunc(x);
    int: 2
    

    And yet another way is using visit or switch:

    visit(bigValue) {
      case Expression e => ...work with e...
    }
    

    The general idea is:

    • pattern matching means narrowing (downcasting)
    • pattern matching may fail and so is always in a conditional context
    • there are many places in Rascal where you can use pattern matching: function dispatch, switch, visit, :=, <-