josh
josh

Reputation: 1554

Data structures in Rascal

I am looking for a data structure that can mimic an Object or a struct. Really, just some compact way to pass around different types of variables. Currently I am using a tuple but referencing various parts of the tuple is less pleasant than I would like. Currently I've just created aliases that represent the various locations in the tuple:

alias AuxClass = tuple[str,str,list[int],list[int],Dec];
int ACLS = 0;

But I've had to restructure this tuple and thus had to change the indexing. Is there something I can use here that I've missed or perhaps a feature coming in the future?

Thanks!

Upvotes: 1

Views: 220

Answers (1)

Mark Hills
Mark Hills

Reputation: 1038

Please take a look at the algebraic data types feature:

http://tutor.rascal-mpl.org/Rascal/Rascal.html#/Rascal/Declarations/AlgebraicDataType/AlgebraicDataType.html

You can create a constructor to represent the type of data that you are trying to define above, similar to what you would do with a struct, and give each element in the constructor a field name:

data AuxClass = auxClass(str f1, str f2, list[int] f3, list[int] f4, Dec f5)

You can then create new instances of this just using the constructor name and providing the data:

a = auxClass("Hello", "World", [1,2,3], [4,5,6], D1) (where D1 is a Dec).

Once you have an instance, you can access information using the field names:

a.f1 // which equals "Hello"

a.f3 // which equals [1,2,3]

size(a.f3) // which currently equals 3

and you can update information using the field names:

a.f2 = "Rascal"

a.f4 = a.f4 + 7 // f4 is now [4,5,6,7]

Algebraic data types are actually quite flexible, so there is a lot you can do with them beyond this. Feel free to look through the documentation and ask questions here.

Upvotes: 2

Related Questions