Rodrigo Bonifacio
Rodrigo Bonifacio

Reputation: 262

Using Rascal MAP

I am trying to create an empty map, that will be then populated within a for loop. Not sure how to proceed in Rascal. For testing purpose, I tried:

rascal>map[int, list[int]] x;
ok

Though, when I try to populate "x" using:

rascal>x += (1, [1,2,3])
>>>>>>>;
>>>>>>>;
        ^ Parse error here

I got a parse error.

Upvotes: 1

Views: 1059

Answers (2)

Jurgen Vinju
Jurgen Vinju

Reputation: 6696

I also like this solution sometimes, where you instead of joining maps just update the value of a certain key:

m = ();
for (...whatever...) {
   m[key]?[] += [1,2,3];
}

In this code, when the key is not yet present in the map, then it starts with the [] empty list and then concatenates [1,2,3] to it, or if the key is present already, let's say it's already at [1,2,3], then this will create [1,2,3,1,2,3] at the specific key in the map.

Upvotes: 2

Mark Hills
Mark Hills

Reputation: 1038

To start, it would be best to assign it an initial value. You don't have to do this at the console, but this is required if you declare the variable inside a script. Also, if you are going to use +=, it has to already have an assigned value.

rascal>map[int,list[int]] x = ( );
map[int, list[int]]: ()

Then, when you are adding items into the map, the key and the value are separated by a :, not by a ,, so you want something like this instead:

rascal>x += ( 1 : [1,2,3]);
map[int, list[int]]: (1:[1,2,3])

rascal>x[1];
list[int]: [1,2,3]

An easier way to do this is to use similar notation to the lookup shown just above:

rascal>x[1] = [1,2,3];
map[int, list[int]]: (1:[1,2,3])

Generally, if you are just setting the value for one key, or are assigning keys inside a loop, x[key] = value is better, += is better if you are adding two existing maps together and saving the result into one of them.

Upvotes: 3

Related Questions