RascalTutor
Synopsis

The available Rascal libraries.

Description

The libraries described here provide the following functionality:

  • Prelude: The Rascal standard prelude.

  • analysis: Library functions for analysis tasks.

  • lang: Definitions and tools for various languages.

  • util: Utilities: functions, data types and interfaces with external libraries.

1. Prelude

Synopsis

The Rascal standard prelude.

Description

The Prelude library provides core functionality for handling all of Rascal’s data-types. See the Rascal Language Reference for details of the language Rascal itself.

For

  • numeric functions, see the Math library,

  • statistical functions see statistics,

  • graph functions see graphs,

  • other common utilitites see util.

Prelude provides the following:

  • Boolean: Library functions for Booleans.

  • Content: Content provides access to the content server of the Rascal terminal for viewing interactive HTML output.

  • DateTime: Library functions for date and time.

  • Exception: Exceptions thrown by the Rascal run-time.

  • IO: Library functions for input/output.

  • List: Library functions for lists.

  • ListRelation: Library functions for list relations.

  • Location: Library functions for source locations.

  • Map: Library functions for maps.

  • Message: A Message datatype that represents messages in the IDE.

  • Node: Library functions for nodes.

  • ParseTree: Library functions for parse trees.

  • Relation: Library functions for relations.

  • Set: Library functions for sets.

  • String: Library functions for strings.

  • Type: Rascal’s type system, implemented in Rascal itself.

  • ValueIO: Library functions for reading and writing values in textual and binary format.

Benefits

This library makes it possible to import all core Rascal functionality with a single import.

Pitfalls
  • The prelude may contain more functionality than you need; this leads to an unnecessary longer import and pollution of your name space.

  • The precise contents of the prelude are under discussion.

  • In the future, Rascal may automatically load the prelude.

1.1. Boolean

Usage

import Boolean;

Synopsis

Library functions for Booleans.

Description

For operators on Boolean values see Boolean in the Rascal Language Reference.

The following functions are defined for Booleans:

  • arbBool: Return an arbitrary Boolean value.

  • fromString: Convert the strings "true" or "false" to a bool

  • toInt: Convert a Boolean value to integer.

  • toReal: Convert Boolean value to real.

  • toString: Convert Boolean value to string.

1.1.1. arbBool

Function

bool arbBool()

Synopsis

Return an arbitrary Boolean value.

Examples
rascal>import Boolean;
ok
rascal>arbBool();
bool: true
rascal>arbBool();
bool: true
rascal>arbBool();
bool: false
Benefits

arbInt is a convenient generator for arbitrary binary choices.

1.1.2. fromString

Function

bool fromString(str s)

Synopsis

Convert the strings "true" or "false" to a bool.

1.1.3. toInt

Function

int toInt(bool b)

Synopsis

Convert a Boolean value to integer.

Description

Maps true to 1 and false to 0.

Examples
rascal>import Boolean;
ok
rascal>toInt(true);
int: 1
rascal>toInt(false);
int: 0

1.1.4. toReal

Function

real toReal(bool b)

Synopsis

Convert Boolean value to real.

Description

Maps true to 1.0 and false to 0.0.

Examples
rascal>import Boolean;
ok
rascal>toReal(true);
real: 1.0
rascal>toReal(false);
real: 0.0

1.1.5. toString

Function

str toString(bool b)

Synopsis

Convert Boolean value to string.

Description

Maps true to "true" and false to "false".

Examples
rascal>import Boolean;
ok
rascal>toString(true);
str: "true"
rascal>toString(false);
str: "false"

1.2. Content

Usage

import Content;

Synopsis

Content provides access to the content server of the Rascal terminal for viewing interactive HTML output.

1.2.1. Content

Types
data Content
     = content(str id, Response (Request) callback)
     | content(Response response)
     ;
Synopsis

Content wraps the HTTP Request/Response API to support interactive visualization types on the terminal [Rascal.REPL].

Description

Values wrapped in a Content wrapper will be displayed by interactive Rascal applications such as the IDE, the REPL terminal and the documentation pages.

For example, a piece of html can be displayed directly like such:

In its most general form, Content is an HTTP(s) webserver callback, such that you might deliver any kind of content, based on any kind of request. If you produce a Content value which processes requests dynamically, subsequent interaction from the web browser will be processed as well. So using the Content wrapper you can start an interactive user experience in the browser directly from the REPL.

Content values stay plugged into the application server that is hidden in the REPL environment until they have not been used for at least 30 minutes. If you want the same interaction back after 30 minutes of non-usage, you have to produce another Content value on the commandline.

When you are happy with the interaction, or you want a permanent visualization which is not garbage collected after 30 minutes, you can consider wrapping the same callback in a webserver using the [util::Webserver::serve] function.

1.2.2. html

Function

Content html(str html)

Synopsis

Directly serve a static html page

1.2.3. file

Function

Content file(loc src)

Synopsis

Directly serve the contents of a file

1.2.4. text

Function

Content text(str text)

Synopsis

Directly serve the contents of a string as plain text

1.2.5. Body

Types

value (type[value] expected)

1.2.6. Request

Types
data Request (map[str, str] headers = (), map[str, str] parameters = (), map[str,str] uploads = ())
     = get (str path)
     | put (str path, Body content)
     | post(str path, Body content)
     | delete(str path)
     | head(str path)
     ;
Synopsis

Request values represent what a browser is asking for, most importantly the URL path.

Description

A request value also contains the full HTTP headers, the URL parameters as a map[str,str] and possibly uploaded content, also coded as a map[str,str]. From the constructor type, put or get you can see what kind of HTTP request it was.

Pitfalls
  • Note that put and post have not been implemented yet in the REPL server.

1.2.7. Response

Types
data Response
     = response(Status status, str mimeType, map[str,str] header, str content)
     | fileResponse(loc file, str mimeType, map[str,str] header)
     | jsonResponse(Status status, map[str,str] header, value val, bool implicitConstructors = true,  bool implicitNodes = true, str dateTimeFormat = "yyyy-MM-dd\'T\'HH:mm:ss\'Z\'")
     ;
Synopsis

A response encodes what is send back from the server to the browser client.

Description

The three kinds of responses, encode either content that is already a str, some file which is streamed directly from its source location or a jsonResponse which involves a handy, automatic, encoding of Rascal values into json values.

1.2.8. response

Function
  • Response response(str content)

  • Response response(Status status, str explanation)

Synopsis

Utility to quickly render a string as HTML content

1.2.9. plain

Function

Response plain(str text)

Synopsis

Utility to quickly make a plaintext response.

1.2.10. response

Function
  • Response response(loc f)

  • default Response response(value val, map[str,str] header = ())

Synopsis

Utility to serve a file from any source location.

1.2.11. Status

Types
data Status
     = ok()
     | created()
     | accepted()
     | noContent()
     | partialContent()
     | redirect()
     | notModified()
     | badRequest()
     | unauthorized()
     | forbidden()
     | notFound()
     | rangeNotSatisfiable()
     | internalError()
     ;
Synopsis

Encoding of HTTP status

1.3. DateTime

Usage

import DateTime;

Synopsis

Library functions for date and time.

Description

For operators on datetime see DateTime in the Rascal Language Reference.

The following functions are defined for datetime:

1.3.1. now

Function

datetime now()

Synopsis

Get the current datetime.

Examples
rascal>import DateTime;
ok
rascal>now();
datetime: $2020-06-05T14:19:31.271+00:00$

1.3.2. createDate

Function

datetime createDate(int year, int month, int day)

Synopsis

Create a new date.

Examples
rascal>import DateTime;
ok
rascal>createDate(2012,1,1);
datetime: $2012-01-01$

1.3.3. createTime

Function
  • datetime createTime(int hour, int minute, int second, int millisecond)

  • datetime createTime(int hour, int minute, int second, int millisecond, int timezoneHourOffset, int timezoneMinuteOffset)

Synopsis

Create a new time (with optional timezone offset).

Examples
rascal>import DateTime;
ok
rascal>createTime(8,15,30,55);
datetime: $T08:15:30.055+01:00$
rascal>createTime(8,15,30,55,2,0);
datetime: $T08:15:30.055+02:00$

1.3.4. createDateTime

Function
  • datetime createDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)

  • datetime createDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int timezoneHourOffset, int timezoneMinuteOffset)

Synopsis

Create a new datetime (with optional timezone offset).

Examples
rascal>import DateTime;
ok
rascal>createDateTime(2012,1,1,8,15,30,55);
datetime: $2012-01-01T08:15:30.055+01:00$
rascal>createDateTime(2012,1,1,8,15,30,55,2,0);
datetime: $2012-01-01T08:15:30.055+02:00$

1.3.5. joinDateAndTime

Function

datetime joinDateAndTime(datetime date, datetime time)

Synopsis

Create a new datetime by combining a date and a time.

Examples
rascal>import DateTime;
ok
rascal>D = createDate(2012, 1, 1);
datetime: $2012-01-01$
rascal>T = createTime(8, 15, 45, 30);
datetime: $T08:15:45.030+01:00$
rascal>joinDateAndTime(D, T);
datetime: $2012-01-01T08:15:45.030+01:00$

1.3.6. splitDateTime

Function

tuple[datetime date, datetime time] splitDateTime(datetime dt)

Synopsis

Split an existing datetime into a tuple with the date and the time.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.445+00:00$
rascal>splitDateTime(N);
tuple[datetime date,datetime time]: <$2020-06-05$,$T14:19:31.445+00:00$>

1.3.7. incrementYears

Function
  • datetime incrementYears(datetime dt, int n)

  • datetime incrementYears(datetime dt)

Synopsis

Increment the years by given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.485+00:00$
rascal>incrementYears(N);
datetime: $2021-06-05T14:19:31.485+00:00$
rascal>incrementYears(N, 5);
datetime: $2025-06-05T14:19:31.485+00:00$

1.3.8. incrementMonths

Function
  • datetime incrementMonths(datetime dt, int n)

  • datetime incrementMonths(datetime dt)

Synopsis

Increment the months by a given amount or by 1. .Function

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.521+00:00$
rascal>incrementMonths(N);
datetime: $2020-07-05T14:19:31.521+00:00$
rascal>incrementMonths(N, 5);
datetime: $2020-11-05T14:19:31.521+00:00$

1.3.9. incrementDays

Function
  • datetime incrementDays(datetime dt, int n)

  • datetime incrementDays(datetime dt)

Synopsis

Increment the days by given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.556+00:00$
rascal>incrementDays(N);
datetime: $2020-06-06T14:19:31.556+00:00$
rascal>incrementDays(N, 5);
datetime: $2020-06-10T14:19:31.556+00:00$

1.3.10. incrementHours

Function
  • datetime incrementHours(datetime dt, int n)

  • datetime incrementHours(datetime dt)

Synopsis

Increment the hours by a given amount or by 1.`

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.602+00:00$
rascal>incrementHours(N);
datetime: $2020-06-05T15:19:31.602+00:00$
rascal>incrementHours(N, 5);
datetime: $2020-06-05T19:19:31.602+00:00$

1.3.11. incrementMinutes

Function
  • datetime incrementMinutes(datetime dt, int n)

  • datetime incrementMinutes(datetime dt)

Synopsis

Increment the minutes by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.638+00:00$
rascal>incrementMinutes(N);
datetime: $2020-06-05T14:20:31.638+00:00$
rascal>incrementMinutes(N, 5);
datetime: $2020-06-05T14:24:31.638+00:00$

1.3.12. incrementSeconds

Function
  • datetime incrementSeconds(datetime dt, int n)

  • datetime incrementSeconds(datetime dt)

Synopsis

Increment the seconds by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.677+00:00$
rascal>incrementSeconds(N);
datetime: $2020-06-05T14:19:32.677+00:00$
rascal>incrementSeconds(N, 5);
datetime: $2020-06-05T14:19:36.677+00:00$

1.3.13. incrementMilliseconds

Function
  • datetime incrementMilliseconds(datetime dt, int n)

  • datetime incrementMilliseconds(datetime dt)

Synopsis

Increment the milliseconds by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.712+00:00$
rascal>incrementMilliseconds(N);
datetime: $2020-06-05T14:19:31.713+00:00$
rascal>incrementMilliseconds(N, 5);
datetime: $2020-06-05T14:19:31.717+00:00$

1.3.14. decrementYears

Function
  • datetime decrementYears(datetime dt, int n)

  • datetime decrementYears(datetime dt)

Synopsis

Decrement the years by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.747+00:00$
rascal>decrementYears(N);
datetime: $2019-06-05T14:19:31.747+00:00$
rascal>decrementYears(N, 5);
datetime: $2015-06-05T14:19:31.747+00:00$

1.3.15. decrementMonths

Function
  • datetime decrementMonths(datetime dt, int n)

  • datetime decrementMonths(datetime dt)

Synopsis

Decrement the months by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.781+00:00$
rascal>decrementMonths(N);
datetime: $2020-05-05T14:19:31.781+00:00$
rascal>decrementMonths(N, 5);
datetime: $2020-01-05T14:19:31.781+00:00$

1.3.16. decrementDays

Function
  • datetime decrementDays(datetime dt, int n)

  • datetime decrementDays(datetime dt)

Synopsis

Decrement the days by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.815+00:00$
rascal>decrementDays(N);
datetime: $2020-06-04T14:19:31.815+00:00$
rascal>decrementDays(N, 3);
datetime: $2020-06-02T14:19:31.815+00:00$

1.3.17. decrementHours

Function
  • datetime decrementHours(datetime dt, int n)

  • datetime decrementHours(datetime dt)

Synopsis

Decrement the hours by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.855+00:00$
rascal>decrementHours(N);
datetime: $2020-06-05T13:19:31.855+00:00$
rascal>decrementHours(N, 5);
datetime: $2020-06-05T09:19:31.855+00:00$

1.3.18. decrementMinutes

Function
  • datetime decrementMinutes(datetime dt, int n)

  • datetime decrementMinutes(datetime dt)

Synopsis

Decrement the minutes by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.890+00:00$
rascal>decrementMinutes(N);
datetime: $2020-06-05T14:18:31.890+00:00$
rascal>decrementMinutes(N, 5);
datetime: $2020-06-05T14:14:31.890+00:00$

1.3.19. decrementSeconds

Function
  • datetime decrementSeconds(datetime dt, int n)

  • datetime decrementSeconds(datetime dt)

Synopsis

Decrement the seconds by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.925+00:00$
rascal>decrementSeconds(N);
datetime: $2020-06-05T14:19:30.925+00:00$
rascal>decrementSeconds(N, 5);
datetime: $2020-06-05T14:19:26.925+00:00$

1.3.20. decrementMilliseconds

Function
  • datetime decrementMilliseconds(datetime dt, int n)

  • datetime decrementMilliseconds(datetime dt)

Synopsis

Decrement the milliseconds by a given amount or by 1.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:31.959+00:00$
rascal>decrementMilliseconds(N);
datetime: $2020-06-05T14:19:31.958+00:00$
rascal>decrementMilliseconds(N, 5);
datetime: $2020-06-05T14:19:31.954+00:00$

1.3.21. interval

Types
data interval
     = Interval(datetime begin, datetime end)
     ;
Synopsis

A closed interval on the time axis.

1.3.22. createInterval

Function

interval createInterval(datetime begin, datetime end)

Synopsis

Given two datetime values, create an interval.

Examples
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2020-06-05T14:19:31.993+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2020-06-07T14:19:31.993+00:00$
rascal>createInterval(B, E);
interval: Interval($2020-06-05T14:19:31.993+00:00$,$2020-06-07T14:19:31.993+00:00$)

1.3.23. Duration

Types
data Duration
     = duration(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds)
     ;
Synopsis

A duration of time, measured in individual years, months, etc.

1.3.24. createDurationInternal

Function

tuple[int,int,int,int,int,int,int] createDurationInternal(datetime begin, datetime end)

1.3.25. createDuration

Function
  • Duration createDuration(datetime begin, datetime end)

  • Duration createDuration(interval i)

Synopsis

Create a new duration representing the duration between the begin and end dates.

Examples
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2020-06-05T14:19:32.034+00:00$
rascal>E1 = incrementHours(B);
datetime: $2020-06-05T15:19:32.034+00:00$
rascal>createDuration(B, E1);
Duration: duration(0,0,0,1,0,0,0)
rascal>E2 = incrementMinutes(B);
datetime: $2020-06-05T14:20:32.034+00:00$
rascal>createDuration(B, E2);
Duration: duration(0,0,0,0,1,0,0)

1.3.26. daysInInterval

Function

int daysInInterval(interval i)

Synopsis

Return the number of days in an interval, including the begin and end days.

Examples
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2020-06-05T14:19:32.071+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2020-06-07T14:19:32.071+00:00$
rascal>I = createInterval(B, E);
interval: Interval($2020-06-05T14:19:32.071+00:00$,$2020-06-07T14:19:32.071+00:00$)
rascal>daysInInterval(I);
int: 2

1.3.27. daysDiff

Function

int daysDiff(datetime begin, datetime end)

Synopsis

Return the difference between two dates and/or datetimes in days.

Examples
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2020-06-05T14:19:32.106+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2020-06-07T14:19:32.106+00:00$
rascal>daysDiff(B, E);
int: 2

1.3.28. dateRangeByDay

Function

list[datetime] dateRangeByDay(interval i)

Synopsis

Given an interval, return a list of days.

Description

Given an interval i, return a list of days [i.begin, …​, i.end].

Examples
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2020-06-05T14:19:32.140+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2020-06-07T14:19:32.140+00:00$
rascal>I = createInterval(B, E);
interval: Interval($2020-06-05T14:19:32.140+00:00$,$2020-06-07T14:19:32.140+00:00$)
rascal>dateRangeByDay(I);
list[datetime]: [$2020-06-05$,$2020-06-06$,$2020-06-07$]

1.3.29. parseDate

Function

datetime parseDate(str inputDate, str formatString)

Synopsis

Parse an input date given as a string using the given format string.

Examples
rascal>import DateTime;
ok
rascal>parseDate("2011-12-23", "yyyy-MM-dd");
datetime: $2011-12-23$
rascal>parseDate("20111223", "yyyyMMdd");
datetime: $2011-12-23$

1.3.30. parseDateInLocale

Function

datetime parseDateInLocale(str inputDate, str formatString, str locale)

Synopsis

Parse an input date given as a string using a specific locale and format string.

1.3.31. parseTime

Function

datetime parseTime(str inputTime, str formatString)

Synopsis

Parse an input time given as a string using the given format string.

Examples
rascal>import DateTime;
ok
rascal>parseTime("11/21/19", "HH/mm/ss");
datetime: $T11:21:19.000+01:00$

1.3.32. parseTimeInLocale

Function

datetime parseTimeInLocale(str inputTime, str formatString, str locale)

Synopsis

Parse an input time given as a string using a specific locale and format string.

1.3.33. parseDateTime

Function

datetime parseDateTime(str inputDateTime, str formatString)

Synopsis

Parse an input datetime given as a string using the given format string.

Examples
rascal>import DateTime;
ok
rascal>parseDateTime("2011/12/23/11/19/54", "YYYY/MM/dd/HH/mm/ss");
datetime: $2010-12-26T11:19:54.000+01:00$

1.3.34. parseDateTimeInLocale

Function

datetime parseDateTimeInLocale(str inputDateTime, str formatString, str locale)

Synopsis

Parse an input datetime given as a string using a specific locale and format string.

1.3.35. printDate

Function
  • str printDate(datetime inputDate, str formatString)

  • str printDate(datetime inputDate)

Synopsis

Print an input date using the given format string.

Examples
rascal>import DateTime;
ok
rascal>printDate(now());
str: "2020-06-05"
rascal>printDate(now(), "YYYYMMdd");
str: "20200605"

1.3.36. printDateInLocale

Function
  • str printDateInLocale(datetime inputDate, str formatString, str locale)

  • str printDateInLocale(datetime inputDate, str locale)

Synopsis

Print an input date using a specific locale and format string.

Examples
rascal>import DateTime;
ok
rascal>printDateInLocale(now(), "Europe/Netherlands");
str: "2020-06-05"
rascal>printDateInLocale(now(), "French");
str: "2020-06-05"

1.3.37. printTime

Function
  • str printTime(datetime inputTime, str formatString)

  • str printTime(datetime inputTime)

Synopsis

Print an input time using the given format string.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:32.353+00:00$
rascal>printTime(N);
str: "14:19:32.353+0000"
rascal>printTime(N, "HH/mm/ss");
str: "14/19/32"

1.3.38. printTimeInLocale

Function
  • str printTimeInLocale(datetime inputTime, str formatString, str locale)

  • str printTimeInLocale(datetime inputTime, str locale)

Synopsis

Print an input time using a specific locale and format string.

1.3.39. printDateTime

Function
  • str printDateTime(datetime inputDateTime, str formatString)

  • str printDateTime(datetime inputDateTime)

Synopsis

Print an input datetime using the given format string.

Examples
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2020-06-05T14:19:32.388+00:00$
rascal>printDateTime(N);
str: "2020-06-05 14:19:32.388+0000"
rascal>printDateTime(N, "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ");
str: "2020-06-05T14:19:32.388+0000"
rascal>printDateTime(N, "YYYY/MM/dd/HH/mm/ss");
str: "2020/06/05/14/19/32"

1.3.40. printDateTimeInLocale

Function
  • str printDateTimeInLocale(datetime inputDateTime, str formatString, str locale)

  • str printDateTimeInLocale(datetime inputDateTime, str locale)

Synopsis

Print an input datetime using a specific locale and format string.

1.3.41. arbDateTime

Function

datetime arbDateTime()

Synopsis

Create a new arbitrary datetime.

Examples
rascal>import DateTime;
ok
rascal>arbDateTime();
datetime: $6423-07-10T21:26:32.913+00:00$

1.4. Exception

Usage

import Exception;

Synopsis

Exceptions thrown by the Rascal run-time.

1.4.1. RuntimeException

Types
data RuntimeException
     = Ambiguity(loc location, str nonterminal, str sentence)
     | ArithmeticException(str message)
     | AssertionFailed()
     | AssertionFailed(str label)
     | EmptyList()
     | EmptyMap()
     | EmptySet()
     | IndexOutOfBounds(int index)
     | IllegalArgument()
     | IllegalArgument(value v)
     | IllegalArgument(value v, str message)
     | InvalidArgument()
     | InvalidArgument(value v)
     | InvalidArgument(value v, str message)
     | InvalidURI(str uri)
     | InvalidUseOfDate(str message)
     | InvalidUseOfLocation(str message)
     | InvalidUseOfTime(str message)
     | IO(str message)
     | Java(str class, str message)
     | Java(str class, str message, RuntimeException cause)
     | JavaException(str class, str message)
     | JavaException(str class, str message, RuntimeException cause)
     | MalFormedURI(str uri)
     | ModuleNotFound(str name)
     | MultipleKey(value key, value first, value second)
     | NoMainFunction()
     | NoSuchAnnotation(str label)
     | NoSuchField(str name)
     | NoSuchKey(value key)
     | NotImplemented(str message)
     | ParseError(loc location)
     | PathNotFound(loc l)
     | PathNotFound(set[loc] locs)
     | RegExpSyntaxError(str message)
     | StackOverflow()
     | UnavailableInformation(str message)
     | ImplodeError(str message)
     | NoSuchElement(value v)
     | PermissionDenied()
     | PermissionDenied(str message)
     | Timeout()
     ;
Synopsis

The Exception datatype used in all Rascal exceptions.

Description

Since declarations for ADTs are extensible, the user can add new exceptions when needed.

Exceptions are either generated by the Rascal run-time (e.g., IndexOutOfBounds) or they are generated by a throw. Exceptions can be caught with a try catch.

Examples

Import relevant libraries:

rascal>import Exception;
ok
rascal>import IO;
ok

Define the map weekend and do a subscription with a non-existing key:

rascal>weekend = ("saturday": 1, "sunday": 2);
map[str, int]: ("sunday":2,"saturday":1)
rascal>weekend["monday"];
|prompt:///|(8,8,<1,8>,<1,16>): NoSuchKey("monday")
	at $shell$(|prompt:///|(0,18,<1,0>,<1,18>))
 
ok

Repeat this, but catch the exception. We use variable N to track what happened:

rascal>N = 1;
int: 1
rascal>try {
>>>>>>>   N = weekend["monday"];
>>>>>>>} catch NoSuchKey(v):
>>>>>>>  N = 100;
ok
rascal>println(N);
100
ok

1.5. IO

Usage

import IO;

Synopsis

Library functions for input/output.

Description

The following input/output functions are defined:

  • registerLocations: register a logical file scheme including the resolution method via a table.

  • unregisterLocations: undo the effect of [registerLocations]

  • resolveLocation:

  • appendToFile: Append a value to a file.

  • appendToFileEnc: Append a value to a file.

  • charsets: Returns all available character sets

  • canEncode: Returns whether this charset can be used for encoding (use with writeFile

  • bprintln: Print a value and return true.

  • exists: Check whether a given location exists.

  • find: Find a named file in a list of locations.

  • isDirectory: Check whether a given location is a directory.

  • iprint: Print an indented representation of a value.

  • iprintToFile: Print an indented representation of a value to the specified location.

  • iprintExp: Print an indented representation of a value and returns the value as result.

  • iprintlnExp: Print an indented representation of a value followed by a newline and returns the value as result.

  • iprintln: Print a indented representation of a value and add a newline at the end.

  • isFile: Check whether a given location is actually a file (and not a directory).

  • lastModified: Last modification date of a location.

  • touch: Set the modification date of a file to now or create the file if it did not exist ye

  • setLastModified: Set the modification date of a file to the timestam

  • listEntries: List the entries in a directory.

  • mkDirectory: Create a new directory.

  • print: Print a value without subsequent newline.

  • printExp: Print a value and return it as result.

  • printExp:

  • println: Print a value to the output stream and add a newline.

  • println:

  • printlnExp: Print a value followed by a newline and return it as result.

  • printlnExp:

  • rprint: Raw print of a value.

  • rprintln: Raw print of a value followed by newline.

  • readFile: Read the contents of a location and return it as string value.

  • readFileEnc: Read the contents of a location and return it as string value.

  • uuencode:

  • readFileBytes: Read the contents of a file and return it as a list of bytes

  • readFileLines: Read the contents of a file location and return it as a list of strings.

  • readFileLinesEnc: Read the contents of a file location and return it as a list of strings.

  • remove:

  • writeFile: Write values to a file.

  • writeFileBytes: Write a list of bytes to a file

  • writeFileEnc: Write values to a file.

  • md5HashFile: Read the contents of a location and return its MD5 hash.

  • createLink:

  • toBase64:

  • copyFile:

  • copyDirectory:

  • arbLoc:

1.5.1. registerLocations

Function

void registerLocations(str scheme, str authority, map[loc logical, loc physical] m)

Synopsis

register a logical file scheme including the resolution method via a table.

Description

Logical source location schemes, such as |java+interface://JRE/java/util/List| are used for precise qualified names of artifacts while abstracting from their physical location in a specific part of a file on disk or from some webserver or source repository location.

Using this function you can create your own schemes. The authority field is used for scoping the names you wish to resolve to certain projects. This way one name can resolve to different locations in different projects.

Benefits
  • Logical source locations are supported by IDE features such as hyperlinks

  • Logical source locations are supported by all IO functions as well

Pitfalls
  • repeated calls to registerLocations for the same scheme and authority will overwrite the m map.

  • the registry is an intentional memory leak; so make sure you use it wisely.

  • when the files references by the physical locations are being written to (edited, removed), then you may expect problems. The registry is not automatically invalidated.

1.5.2. unregisterLocations

Function

void unregisterLocations(str scheme, str authority)

Synopsis

undo the effect of [registerLocations]

Description

For debugging or for memory management you may wish to remove a lookup table.

1.5.3. resolveLocation

Function

loc resolveLocation(loc l)

1.5.4. appendToFile

Function

void appendToFile(loc file, value V…​) throws PathNotFound, IO

Synopsis

Append a value to a file.

Description

Append a textual representation of some values to an existing or a newly created file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.

  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.

  • All other values are printed as-is.

  • Each value is terminated by a newline character.

Encoding

The existing file can be stored using any character set possible, if you know the character set, please use appendToFileEnc. Else the same method of deciding the character set is used as in readFile.

Pitfalls
  • The same encoding pitfalls as the readFile function.

1.5.5. appendToFileEnc

Function

void appendToFileEnc(loc file, str charset, value V…​) throws PathNotFound, IO

Synopsis

Append a value to a file.

Description

Append a textual representation of some values to an existing or a newly created file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.

  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.

  • All other values are printed as-is.

  • Each value is terminated by a newline character.

Files are encoded using the charset provided.

1.5.6. charsets

Function

set[str] charsets()

Synopsis

Returns all available character sets.

1.5.7. canEncode

Function

set[str] canEncode(str charset)

Synopsis

Returns whether this charset can be used for encoding (use with writeFile)

1.5.8. bprintln

Function

bool bprintln(value arg)

Synopsis

Print a value and return true.

Description

Print a value and return true. This is useful for debugging complex Boolean expressions or comprehensions. The only difference between this function and println is that its return type is bool rather than void.

Examples
rascal>import IO;
ok
rascal>bprintln("Hello World");
Hello World
bool: true

1.5.9. exists

Function

bool exists(loc file)

Synopsis

Check whether a given location exists.

Description

Check whether a certain location exists, i.e., whether an actual file is associated with it.

Examples
rascal>import IO;
ok

Does the library file IO.rsc exist?

rascal>exists(|std:///IO.rsc|);
bool: true

1.5.10. find

Function

loc find(str name, list[loc] path) throws PathNotFound

Synopsis

Find a named file in a list of locations.

Examples
rascal>import IO;
ok

Find the file IO.rsc in the standard library:

rascal>find("IO.rsc", [|std:///|]);
loc: |std:///IO.rsc|

1.5.11. isDirectory

Function

bool isDirectory(loc file)

Synopsis

Check whether a given location is a directory.

Description

Check whether the location file is a directory.

1.5.12. iprint

Function

void iprint(value arg, int lineLimit = 1000)

Synopsis

Print an indented representation of a value.

Description

See iprintExp for a version that returns its argument as result and iprintln for a version that adds a newline and iprintToFile for a version that prints to a file.

Examples
rascal>import IO;
ok
rascal>iprint(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
[
  "fruits",
  ("snake":0,"spider":8),
  [10,20,30]
]ok

1.5.13. iprintToFile

Function

void iprintToFile(loc file, value arg)

Synopsis

Print an indented representation of a value to the specified location.

Description

See iprint for a version that displays the result on the console and iprintExp for a version that returns its argument as result and iprintln for a version that adds a newline.

Examples
rascal>import IO;
ok
rascal>iprintToFile(|file:///tmp/fruits.txt|, ["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
ok

1.5.14. iprintExp

Function

&T iprintExp(&T v)

Synopsis

Print an indented representation of a value and returns the value as result.

Description

See iprintlnExp for a version that adds a newline.

Examples
rascal>import IO;
ok
rascal>iprintExp(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
[
  "fruits",
  ("snake":0,"spider":8),
  [10,20,30]
]list[value]: [
  "fruits",
  ("snake":0,"spider":8),
  [10,20,30]
]

1.5.15. iprintlnExp

Function

&T iprintlnExp(&T v)

Synopsis

Print an indented representation of a value followed by a newline and returns the value as result.

Description

See iprintExp for a version that does not add a newline.

Examples
rascal>import IO;
ok
rascal>iprintlnExp(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
[
  "fruits",
  ("snake":0,"spider":8),
  [10,20,30]
]
list[value]: [
  "fruits",
  ("snake":0,"spider":8),
  [10,20,30]
]

1.5.16. iprintln

Function

void iprintln(value arg, int lineLimit = 1000)

Synopsis

Print a indented representation of a value and add a newline at the end.

Description

See iprintlnExp for a version that returns its argument as result and iprint for a version that does not add a newline.

By default we only print the first 1000 lines, if you want to print larger values, either use writeTextValueFile or change the limit with the lineLimit parameter.

Examples
rascal>import IO;
ok
rascal>iprintln(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
[
  "fruits",
  ("snake":0,"spider":8),
  [10,20,30]
]
ok
rascal>iprintln([ {"hi"} | i <- [0..1000]], lineLimit = 10);
[
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
  {"hi"},
…​
ok

1.5.17. isFile

Function

bool isFile(loc file)

Synopsis

Check whether a given location is actually a file (and not a directory).

Description

Check whether location file is actually a file.

1.5.18. lastModified

Function

datetime lastModified(loc file)

Synopsis

Last modification date of a location.

Description

Returns last modification time of the file at location file.

Examples
rascal>import IO;
ok

Determine the last modification date of the Rascal standard library:

rascal>lastModified(|std:///IO.rsc|);
datetime: $2020-06-05T13:54:18.000+00:00$

1.5.19. touch

Function

void touch(loc file)

Synopsis

Set the modification date of a file to now or create the file if it did not exist yet

1.5.20. setLastModified

Function

void setLastModified(loc file, datetime timestamp)

Synopsis

Set the modification date of a file to the timestamp

1.5.21. listEntries

Function

list[str] listEntries(loc file)

Synopsis

List the entries in a directory.

Description

List the entries in directory file.

Examples
rascal>import IO;
ok

List all entries in the standard library:

rascal>listEntries(|std:///|);
list[str]: ["Boolean.rsc","Map.rsc","Relation.rsc","DateTime.rsc","demo","Prelude.class","Prelude$NodeComparator.class","ValueIO.rsc","ParseTree.rsc","Prelude$Backtrack.class","Traversal.rsc","Set.rsc","ListRelation.rsc","Prelude$1.class","Prelude.rsc","resource",".project","List.rsc","Node.rsc","Type.rsc","String.rsc","Location.rsc","IO.rsc","util","Content.rsc","Exception.rsc","Prelude$Sorting.class","Message.rsc","Type.class","Prelude$Distance.class","lang","experiments","Prelude$Less.class","analysis","Prelude$ByteBufferBackedInputStream.class","Grammar.rsc"]

1.5.22. mkDirectory

Function

void mkDirectory(loc file) throws PathNotFound, IO

Synopsis

Create a new directory.

Description

Create a directory at location file.

1.5.23. print

Function

void print(value arg)

Synopsis

Print a value without subsequent newline.

Description

Print a value on the output stream. See println for a version that adds a newline and printExp for a version that returns its argument as value.

Examples

Note that the only difference with println is that no newline is added after the value is printed

rascal>import IO;
ok
rascal>print("Hello World");
Hello Worldok
Since print does not add a newline, the prompt ok appears at a weird place, i.e., glued to the output of print.

1.5.24. printExp

Function
  • &T printExp(&T v)

  • &T printExp(str msg, &T v)

Synopsis

Print a value and return it as result.

Examples
rascal>import IO;
ok
rascal>printExp(3.14);
3.14real: 3.14
rascal>printExp("The value of PI is approximately ", 3.14);
The value of PI is approximately 3.14real: 3.14

1.5.25. println

Function
  • void println(value arg)

  • void println()

Synopsis

Print a value to the output stream and add a newline.

Description

Print a value on the output stream followed by a newline. See print for a version that does not add a newline and printlnExp for a version that returns its argument as value.

Examples
rascal>import IO;
ok
rascal>println("Hello World");
Hello World
ok

Introduce variable S and print it:

rascal>S = "Hello World";
str: "Hello World"
rascal>println(S);
Hello World
ok

Introduce variable L and print it:

rascal>L = ["a", "b", "c"];
list[str]: ["a","b","c"]
rascal>println(L);
["a","b","c"]
ok

Use a string template to print several values:

rascal>println("<S>: <L>");
Hello World: ["a","b","c"]
ok

Just print a newline

rascal>println();

ok

1.5.26. printlnExp

Function
  • &T printlnExp(&T v)

  • &T printlnExp(str msg, &T v)

Synopsis

Print a value followed by a newline and return it as result.

Examples
rascal>import IO;
ok
rascal>printlnExp(3.14);
3.14
real: 3.14
rascal>printlnExp("The value of PI is approximately ", 3.14);
The value of PI is approximately 3.14
real: 3.14
Since printExp does no produce a newline after its output, the result prompt real: 3.14 is glued to the output of printExp.

1.5.27. rprint

Function

void rprint(value arg)

Synopsis

Raw print of a value.

Pitfalls

This function is only available for internal use in the Rascal development team.

1.5.28. rprintln

Function

void rprintln(value arg)

Synopsis

Raw print of a value followed by newline.

Pitfalls

This function is only available for internal use in the Rascal development team.

1.5.29. readFile

Function

str readFile(loc file) throws PathNotFound, IO

Synopsis

Read the contents of a location and return it as string value.

Description

Return the contents of a file location as a single string. Also see readFileLines.

Encoding

A text file can be encoded in many different character sets, most common are UTF8, ISO-8859-1, and ASCII. If you know the encoding of the file, please use the readFileEnc and readFileLinesEnc overloads. If you do not know, we try to detect this. This detection is explained below:

  • If the implementation of the used scheme in the location (e.g.,|project:///|) defines the charset of the file then this is used.

  • Otherwise if the file contains a UTF8/16/32 BOM, then this is used.

  • As a last resort the IO library uses heuristics to determine if UTF-8 or UTF-32 could work:

    • Are the first 32 bytes valid UTF-8? Then use UTF-8.

    • Are the first 32 bytes valid UTF-32? Then use UTF-32.

  • Finally, we fall back to the system default (as given by the Java Runtime Environment).

To summarize, we use UTF-8 by default, except if the location has available meta-data, the file contains a BOM, or the first 32 bytes of the file are not valid UTF-8.

Pitfalls
  • The second version of readFile with a string argument is deprecated.

  • In case encoding is not known, we try to estimate as best as we can.

  • We default to UTF-8, if the file was not encoded in UTF-8 but the first characters were valid UTF-8, you might get an decoding error or just strange looking characters.

1.5.30. readFileEnc

Function

str readFileEnc(loc file, str charset) throws PathNotFound, IO

Synopsis

Read the contents of a location and return it as string value.

Description

Return the contents (decoded using the Character set supplied) of a file location as a single string. Also see readFileLinesEnc.

1.5.31. uuencode

Function

str uuencode(loc file) throws PathNotFound, IO

1.5.32. readFileBytes

Function

list[int] readFileBytes(loc file) throws PathNotFound, IO

Synopsis

Read the contents of a file and return it as a list of bytes.

1.5.33. readFileLines

Function

list[str] readFileLines(loc file) throws PathNotFound, IO

Synopsis

Read the contents of a file location and return it as a list of strings.

Description

Return the contents of a file location as a list of lines. Also see readFile.

Encoding

Look at readFile to understand how this function chooses the character set. If you know the character set used, please use readFileLinesEnc.

Pitfalls
  • In case encoding is not known, we try to estimate as best as we can (see [readFile]).

  • We default to UTF-8, if the file was not encoded in UTF-8 but the first characters were valid UTF-8, you might get an decoding error or just strange looking characters (see readFile).

1.5.34. readFileLinesEnc

Function

list[str] readFileLinesEnc(loc file, str charset) throws PathNotFound, IO

Synopsis

Read the contents of a file location and return it as a list of strings.

Description

Return the contents (decoded using the Character set supplied) of a file location as a list of lines. Also see readFileLines.

1.5.35. remove

Function

void remove(loc file) throws IO

1.5.36. writeFile

Function

void writeFile(loc file, value V…​) throws PathNotFound, IO

Synopsis

Write values to a file.

Description

Write a textual representation of some values to a file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.

  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.

  • All other values are printed as-is.

  • Each value is terminated by a newline character.

Files are encoded in UTF-8, in case this is not desired, use writeFileEnc.

1.5.37. writeFileBytes

Function

void writeFileBytes(loc file, list[int] bytes) throws PathNotFound, IO

Synopsis

Write a list of bytes to a file.

1.5.38. writeFileEnc

Function

void writeFileEnc(loc file, str charset, value V…​) throws PathNotFound, IO

Synopsis

Write values to a file.

Description

Write a textual representation of some values to a file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.

  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.

  • All other values are printed as-is.

  • Each value is terminated by a newline character.

Files are encoded using the charset provided.

1.5.39. md5HashFile

Function

str md5HashFile(loc file) throws PathNotFound, IO

Synopsis

Read the contents of a location and return its MD5 hash.

Description

MD5 hash the contents of a file location.

Function

str createLink(str title, str target)

1.5.41. toBase64

Function

str toBase64(loc file) throws PathNotFound, IO

1.5.42. copyFile

Function

bool copyFile(loc source, loc target)

1.5.43. copyDirectory

Function

bool copyDirectory(loc source, loc target)

1.5.44. arbLoc

Function

loc arbLoc()

1.6. List

Usage

import List;

Synopsis

Library functions for lists.

Description

For operators on lists see List in the Rascal Language Reference.

The following functions are available for lists:

  • concat: Concatenate a list of lists.

  • delete: Delete an element from a list.

  • distribution: Get the distribution of the elements of the list. That

  • drop: Drop elements from the head of a list.

  • dup: Remove multiple occurrences of elements in a list. The first occurrence remains.

  • elementAt:

  • getOneFrom: Pick a random element from a list.

  • getFirstFrom: Pick first element from a list.

  • head: Get the first element(s) from a list.

  • head:

  • headTail: Split a list in a head and a tail.

  • index: A list of legal index values of a list.

  • indexOf: Index of first occurrence of an element in a list.

  • insertAt: Insert an element at a specific position in a list.

  • intercalate: Join a list of values into a string separated by a separator.

  • intersperse: Intersperses a list of values with a separator.

  • isEmpty: Test whether a list is empty.

  • last: Return the last element of a list, if any.

  • lastIndexOf: Return index of last occurrence of elt in lst, or -1 if elt is not found.

  • mapper: Apply a function to all list elements and return list of results.

  • max: Determine the largest element in a list.

  • merge: Merge the elements of two sorted lists into one list.

  • merge:

  • min: Determine the smallest element in a list.

  • mix: Mix the elements of two lists.

  • permutations: Compute all permutations of a list.

  • permutationsBag:

  • pop: Pop top element from list, return a tuple.

  • prefix: Return all but the last element of a list.

  • push: Push an element in front of a list.

  • reducer: Apply a function to successive elements of list and combine the results (deprecated).

  • remove:

  • removeFromBag:

  • removeFromBag:

  • reverse: Reverse a list.

  • size: Determine the number of elements in a list.

  • slice: Compute a sublist of a list.

  • sort: Sort the elements of a list.

  • sort:

  • shuffle: Shuffle a list.

  • shuffle: Shuffle a list with a seed.

  • split: Split a list into two halves.

  • sum:

  • sum: Sum the elements of a list.

  • tail: Get the tail element(s) from a list.

  • tail:

  • take: Get number of elements from the head of a list.

  • takeOneFrom: Remove an arbitrary element from a list, returns the element and the modified list.

  • takeWhile: Take elements from the front of the list as long as a predicate is true.

  • toMap: Convert a list of pairs to a map; first elements are associated with a set of second elements.

  • toMapUnique: Convert a list of tuples to a map; result must be a map.

  • top: Take the top element of a list.

  • toRel: Convert a list to a relation.

  • toSet: Convert a list to a set.

  • toString: Convert a list to a string.

  • itoString: Convert a list to an indented string.

  • unzip: Make a pair (triple) of lists from a list of pairs (triples).

  • unzip:

  • upTill: Returns the list 0,1..n-1.

  • zip: Make a list of pairs from two (three) lists of the same length.

  • zip:

1.6.1. concat

Function

list[&T] concat(list[list[&T]] xxs)

Synopsis

Concatenate a list of lists.

Examples
rascal>import List;
ok
rascal>concat([]);
list[void]: []
rascal>concat([[]]);
list[void]: []
rascal>concat([[1]]);
list[int]: [1]
rascal>concat([[1],[],[2,3]]);
list[int]: [1,2,3]
rascal>concat([[1,2],[3],[4,5],[]]);
list[int]: [1,2,3,4,5]

1.6.2. delete

Function

list[&T] delete(list[&T] lst, int n)

Synopsis

Delete an element from a list.

Description

Delete the n-th element from a list. A new list without the n-th element is returned as result. The IndexOutOfBounds exception is thrown when n is not a valid index.

Examples
rascal>import List;
ok
rascal>delete([1, 2, 3], 1);
list[int]: [1,3]
rascal>delete(["zebra", "elephant", "snake", "owl"], 2);
list[str]: ["zebra","elephant","owl"]

1.6.3. distribution

Function

map[&T element, int occurs] distribution(list[&T] lst)

Synopsis

Get the distribution of the elements of the list. That is how often does each element occur in the list?

Examples
rascal>import List;
ok
rascal>distribution([4,4,4,3,1,2,1,1,3,4]);
map[int element, int occurs]: (1:3,3:2,2:1,4:4)

1.6.4. drop

Function

list[&T] drop(int n, list[&T] lst)

Synopsis

Drop elements from the head of a list.

Description

Drop n elements (or size(lst) elements if size(lst) < n) from the head of lst. See take to get elements from the head of a list].

Examples
rascal>import List;
ok
rascal>drop(2, [5, 1, 7, 3]);
list[int]: [7,3]
rascal>drop(10, [5, 1, 7, 3]);
list[int]: []
rascal>drop(2, ["zebra", "elephant", "snake", "owl"]);
list[str]: ["snake","owl"]

1.6.5. dup

Function

list[&T] dup(list[&T] lst)

Synopsis

Remove multiple occurrences of elements in a list. The first occurrence remains.

Examples
rascal>import List;
ok
rascal>dup([3, 1, 5, 3, 1, 7, 1, 2]);
list[int]: [3,1,5,7,2]

1.6.6. elementAt

Function

&T elementAt(list[&T] lst, int index)

1.6.7. getOneFrom

Function

&T getOneFrom(list[&T] lst)

Synopsis

Pick a random element from a list.

Description

Get an arbitrary element from a list. See takeOneFrom for a function that also removes the selected element.

Examples
rascal>import List;
ok
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "elephant"
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "snake"
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "snake"

1.6.8. getFirstFrom

Function

&T getFirstFrom(list[&T] lst)

Synopsis

Pick first element from a list.

Description

Get the first element from a list. As opposed to getOneFrom this function always returns the same (first) list element.

1.6.9. head

Function
  • &T head(list[&T] lst) throws EmptyList

  • list[&T] head(list[&T] lst, int n) throws IndexOutOfBounds

Synopsis

Get the first element(s) from a list.

Description
  • Returns the first element of a list or throws EmptyList when the list is empty. This is identical to [top].

  • Returns the first n elements of a list or throws IndexOutOfBounds when the list is too short. This is similar to [take].

Examples
rascal>import List;
ok

Get the first element:

rascal>head([1, 2, 3]);
int: 1
rascal>head(["zebra", "elephant", "snake", "owl"]);
str: "zebra"

An exception is thrown when taking the head of an empty list:

rascal>head([]);
|std:///List.rsc|(3534,1019,<153,0>,<192,51>): EmptyList()
	at *** somewhere ***(|std:///List.rsc|(3534,1019,<153,0>,<192,51>))
	at head(|prompt:///|(5,2,<1,5>,<1,7>))
 
ok

Get the first n elements:

rascal>head([1, 2, 3, 4], 2);
list[int]: [1,2]
rascal>head(["zebra", "elephant", "snake", "owl"], 2);
list[str]: ["zebra","elephant"]

An exception is thrown when the second argument exceeds the length of the list:

rascal>head([1, 2, 3, 5], 5);
|std:///List.rsc|(4593,113,<195,0>,<196,71>): IndexOutOfBounds(4)
	at *** somewhere ***(|std:///List.rsc|(4593,113,<195,0>,<196,71>))
	at head(|prompt:///|(19,1,<1,19>,<1,20>))
 
ok

1.6.10. headTail

Function

tuple[&T, list[&T]] headTail(list[&T] lst) throws EmptyList

Synopsis

Split a list in a head and a tail.

Description

This function is identical to pop.

Examples
rascal>import List;
ok
rascal>headTail([3, 1, 4, 5]);
tuple[int,list[int]]: <3,[1,4,5]>
rascal>pop([3, 1, 4, 5]);
tuple[int,list[int]]: <3,[1,4,5]>
rascal>headTail(["zebra", "elephant", "snake", "owl"]);
tuple[str,list[str]]: <"zebra",["elephant","snake","owl"]>

1.6.11. index

Function

list[int] index(list[&T] lst)

Synopsis

A list of legal index values of a list.

Description

Returns a list of all legal index values for a given list lst.

Examples
rascal>import List;
ok
rascal>index([1, 3, 5]);
list[int]: [0,1,2]
rascal>index(["zebra", "elephant", "snake", "owl"]);
list[int]: [0,1,2,3]
Benefits

This function is useful in for loops over lists.

1.6.12. indexOf

Function

int indexOf(list[&T] lst, &T elt)

Synopsis

Index of first occurrence of an element in a list.

Description

Return index of first occurrence of elt in lst, or -1 if elt is not found. Also see lastIndexOf.

Examples
rascal>import List;
ok
rascal>indexOf([3, 1, 4, 5], 4);
int: 2
rascal>indexOf([3, 1, 4, 5], 7);
int: -1
rascal>indexOf(["zebra", "elephant", "snake", "owl"], "snake");
int: 2
rascal>indexOf(["zebra", "elephant", "snake", "owl"], "eagle");
int: -1

1.6.13. insertAt

Function

list[&T] insertAt(list[&T] lst, int n, &T elm) throws IndexOutOfBounds

Synopsis

Insert an element at a specific position in a list.

Description

Returns a new list with the value of elm inserted at index position n of the old list.

Examples
rascal>import List;
ok
rascal>insertAt([1,2,3], 1, 5);
list[int]: [1,5,2,3]
rascal>insertAt(["zebra", "elephant", "snake", "owl"], 2, "eagle");
list[str]: ["zebra","elephant","eagle","snake","owl"]

An exception is thrown when the index position is outside the list:

rascal>insertAt([1,2,3], 10, 5);
|std:///List.rsc|(6061,588,<264,0>,<284,83>): IndexOutOfBounds(10)
	at *** somewhere ***(|std:///List.rsc|(6061,588,<264,0>,<284,83>))
	at insertAt(|prompt:///|(22,1,<1,22>,<1,23>))
 
ok

1.6.14. intercalate

Function

str intercalate(str sep, list[value] l)

Synopsis

Join a list of values into a string separated by a separator.

Examples
rascal>import List;
ok
rascal>intercalate("/", [3]);
str: "3"
rascal>intercalate("/", [3, 1, 4, 5]);
str: "3/1/4/5"
rascal>intercalate(", ", [3, 1, 4, 5]);
str: "3, 1, 4, 5"
rascal>intercalate(", ", ["zebra", "elephant", "snake", "owl"]);
str: "zebra, elephant, snake, owl"

1.6.15. intersperse

Function

list[&T] intersperse(&T sep, list[&T] xs)

Synopsis

Intersperses a list of values with a separator.

Examples
rascal>import List;
ok
rascal>intersperse(", ", ["a","b","c"]);
list[str]: ["a",", ","b",", ","c"]
rascal>intersperse(0, [1, 2, 3]);
list[int]: [1,0,2,0,3]
rascal>intersperse(1, []);
list[int]: []
rascal>intersperse([], [1]);
list[value]: [1]

1.6.16. isEmpty

Function

bool isEmpty(list[&T] lst)

Synopsis

Test whether a list is empty.

Description

Returns true when a list is empty and false otherwise.

Examples
rascal>import List;
ok
rascal>isEmpty([]);
bool: true
rascal>isEmpty([1, 2, 3]);
bool: false

1.6.17. last

Function

&T last(list[&T] lst) throws EmptyList

Synopsis

Return the last element of a list, if any.

Description

Also see tail that returns a list of one or more of the last elements of a list.

Examples
rascal>import List;
ok
rascal>last([1]);
int: 1
rascal>last([3, 1, 4, 5]);
int: 5
rascal>last(["zebra", "elephant", "snake", "owl"]);
str: "owl"
rascal>tail([3, 1, 4, 5]);
list[int]: [1,4,5]

1.6.18. lastIndexOf

Function

int lastIndexOf(list[&T] lst, &T elt)

Synopsis

Return index of last occurrence of elt in lst, or -1 if elt is not found.

Description

Also see indexOf.

Examples
rascal>import List;
ok
rascal>lastIndexOf([3, 1, 4, 5, 4], 4);
int: 4
rascal>lastIndexOf([3, 1, 4, 5, 4], 7);
int: -1
rascal>lastIndexOf(["zebra", "owl", "elephant", "snake", "owl"], "owl");
int: 4

1.6.19. mapper

Function

list[&U] mapper(list[&T] lst, &U (&T) fn)

Synopsis

Apply a function to all list elements and return list of results.

Description

Apply a function fn to each element of lst and return the list of results.

Examples
rascal>import List;
ok
rascal>int incr(int x) { return x + 1; }
int (int): function(|prompt:///|(0,33,<1,0>,<1,33>))
rascal>mapper([1, 2, 3, 4], incr);
list[int]: [2,3,4,5]

1.6.20. max

Function

&T max(list[&T] lst) throws EmptyList

Synopsis

Determine the largest element in a list.

Examples
rascal>import List;
ok
rascal>max([1, 3, 5, 2, 4]);
int: 5
rascal>max(["zebra", "elephant", "snake", "owl"]);
str: "zebra"

1.6.21. merge

Function
  • list[&T] merge(list[&T] left, list[&T] right)

  • list[&T] merge(list[&T] left, list[&T] right, bool (&T a, &T b) lessOrEqual)

Synopsis

Merge the elements of two sorted lists into one list.

Description

Merge the elements of two sorted lists into one list using the built-in ordering between values. Optional, a comparison function lessOrEqual may be given for a user-defined ordering between values.

Examples
rascal>import List;
ok
rascal>merge([1, 3, 5], [2, 7, 9, 15]);
list[int]: [1,2,3,5,7,9,15]
rascal>merge(["ape", "elephant", "owl", "snale", "zebra"], ["apple", "berry", "orange", "pineapple"]);
list[str]: ["ape","apple","berry","elephant","orange","owl","pineapple","snale","zebra"]

Merge two lists of strings and use their length as ordering:

rascal>import String;
ok
rascal>merge(["ape", "owl", "snale", "zebra", "elephant"], ["apple", "berry", "orange", "pineapple"], bool(str x, str y){ return size(x) <= size(y); });
list[str]: ["ape","owl","snale","zebra","apple","berry","orange","elephant","pineapple"]

1.6.22. min

Function

&T min(list[&T] lst)

Synopsis

Determine the smallest element in a list.

Examples
rascal>import List;
ok
rascal>min([1, 3, 5, 2, 4]);
int: 1
rascal>min(["zebra", "elephant", "snake", "owl"]);
str: "elephant"

1.6.23. mix

Function

list[&T] mix(list[&T] l, list[&T] r)

Synopsis

Mix the elements of two lists.

Description

Let n be the minimum of the length of the two lists l and r. mix returns a list in which the first n elements are taken alternately from the left and the right list, followed by the remaining elements of the longest list.

Examples
rascal>import List;
ok
rascal>mix([3, 1, 7, 5, 9], [15, 25, 35]);
list[int]: [3,15,1,25,7,35,5,9]
rascal>mix([3, 1, 7], [15, 25, 35, 45, 55]);
list[int]: [3,15,1,25,7,35,45,55]
rascal>mix([3, 1, 7], ["elephant", "snake"]);
list[value]: [3,"elephant",1,"snake",7]

1.6.24. permutations

Function

set[list[&T]] permutations(list[&T] lst)

Synopsis

Compute all permutations of a list.

Examples
rascal>import List;
ok
rascal>permutations([1,2,3]);
set[list[int]]: {
  [3,2,1],
  [1,2,3],
  [2,1,3],
  [1,3,2],
  [2,3,1],
  [3,1,2]
}

1.6.25. permutationsBag

Function

set[list[&T]] permutationsBag(map[&T element, int occurs] b)

1.6.26. pop

Function

tuple[&T, list[&T]] pop(list[&T] lst) throws EmptyList

Synopsis

Pop top element from list, return a tuple. .Description This function is identical to headTail. Also see push and top.

Examples
rascal>import List;
ok
rascal>pop([3, 1, 4, 5]);
tuple[int,list[int]]: <3,[1,4,5]>
rascal>headTail([3, 1, 4, 5]);
tuple[int,list[int]]: <3,[1,4,5]>
rascal>pop(["zebra", "elephant", "snake", "owl"]);
tuple[str,list[str]]: <"zebra",["elephant","snake","owl"]>

1.6.27. prefix

Function

list[&T] prefix(list[&T] lst)

Synopsis

Return all but the last element of a list.

Examples
rascal>import List;
ok
rascal>prefix([3, 1, 4, 5]);
list[int]: [3,1,4]
rascal>prefix([]);
list[void]: []
rascal>prefix(["zebra", "elephant", "snake", "owl"]);
list[str]: ["zebra","elephant","snake"]

1.6.28. push

Function

list[&T] push(&T elem, list[&T] lst)

Synopsis

Push an element in front of a list.

Description

Also see pop and top.

Examples
rascal>import List;
ok
rascal>push(7, [3, 1, 4, 5]);
list[int]: [7,3,1,4,5]
rascal>push("eagle", ["zebra", "elephant", "snake", "owl"]);
list[str]: ["eagle","zebra","elephant","snake","owl"]

1.6.29. reducer

Function

&T reducer(list[&T] lst, &T (&T, &T) fn, &T unit)

Synopsis

Apply a function to successive elements of list and combine the results (deprecated).

Description

Apply the function fn to successive elements of list lst starting with unit.

Examples
rascal>import List;
ok
rascal>int add(int x, int y) { return x + y; }
int (int, int): function(|prompt:///|(0,39,<1,0>,<1,39>))
rascal>reducer([10, 20, 30, 40], add, 0);
int: 100
Pitfalls

WARNING: This function is deprecated, use a reducer instead.

1.6.30. remove

Function

list[&T] remove(list[&T] lst, int indexToDelete)

1.6.31. removeFromBag

Function
  • map[&T element, int occurs] removeFromBag(map[&T element, int occurs] b, &T el)

  • map[&T element, int occurs] removeFromBag(map[&T element, int occurs] b, &T el, int nr)

1.6.32. reverse

Function

list[&T] reverse(list[&T] lst)

Synopsis

Reverse a list.

Description

Returns a list with the elements of lst in reverse order.

Examples
rascal>import List;
ok
rascal>reverse([1,4,2,3]);
list[int]: [3,2,4,1]
rascal>reverse(["zebra", "elephant", "snake", "owl"]);
list[str]: ["owl","snake","elephant","zebra"]

1.6.33. size

Function

int size(list[&T] lst)

Synopsis

Determine the number of elements in a list.

Examples
rascal>import List;
ok
rascal>size([20, 10, 30]);
int: 3
rascal>size(["zebra", "elephant", "snake", "owl"]);
int: 4

1.6.34. slice

Function

list[&T] slice(list[&T] lst, int begin, int len)

Synopsis

Compute a sublist of a list.

Description

Returns a sublist of lst from index start of length len.

In most cases it is better to use the built-in slice notation, see the example below.
Examples
rascal>import List;
ok
rascal>slice([10, 20, 30, 40, 50, 60], 2, 3);
list[int]: [30,40,50]
rascal>slice(["zebra", "elephant", "snake", "owl"], 1, 2);
list[str]: ["elephant","snake"]

Here are the equivalent expressions using the slice notation:

rascal>[10, 20, 30, 40, 50, 60][2 .. 5];
list[int]: [30,40,50]
rascal>["zebra", "elephant", "snake", "owl"][1 .. 3];
list[str]: ["elephant","snake"]
In the slice notation the upper bound is exclusive.

1.6.35. sort

Function
  • list[&T] sort(list[&T] lst)

  • list[&T] sort(list[&T] l, bool (&T a, &T b) less)

Synopsis

Sort the elements of a list.

Description

Sort the elements of a list:

  • Use the built-in ordering on values to compare list elements.

  • Give an additional lessThan function that will be used to compare elements.

Examples
rascal>import List;
ok
rascal>import String;
ok
rascal>sort([10, 4, -2, 11, 100, 5]);
list[int]: [-2,4,5,10,11,100]
rascal>fruits = ["mango", "strawberry", "pear", "pineapple", "banana", "grape", "kiwi"];
list[str]: ["mango","strawberry","pear","pineapple","banana","grape","kiwi"]
rascal>sort(fruits);
list[str]: ["banana","grape","kiwi","mango","pear","pineapple","strawberry"]
rascal>sort(fruits, bool(str a, str b){ return size(a) > size(b); });
list[str]: ["strawberry","pineapple","banana","grape","mango","pear","kiwi"]

1.6.36. shuffle

Function
  • list[&T] shuffle(list[&T] l)

  • list[&T] shuffle(list[&T] l, int seed)

Synopsis

Shuffle a list.

Description

Returns a random (unbiased) shuffled list.

Examples
rascal>import List;
ok
rascal>shuffle([1,4,2,3]);
list[int]: [1,3,2,4]
rascal>shuffle(["zebra", "elephant", "snake", "owl"]);
list[str]: ["zebra","snake","owl","elephant"]

1.6.37. split

Function

tuple[list[&T],list[&T]] split(list[&T] l)

Synopsis

Split a list into two halves.

Examples
rascal>import List;
ok
rascal>split([3, 1, 4, 5, 7]);
tuple[list[int],list[int]]: <[3,1],[4,5,7]>
rascal>split(["zebra", "elephant", "snake", "owl"]);
tuple[list[str],list[str]]: <["zebra","elephant"],["snake","owl"]>

1.6.38. sum

Function
  • (&T <:num) sum(list[(&T <:num)] _:[])

  • default (&T <:num) sum([(&T <: num) hd, *(&T <: num) tl])

1.6.39. tail

Function
  • list[&T] tail(list[&T] lst) throws EmptyList

  • list[&T] tail(list[&T] lst, int len) throws IndexOutOfBounds

Synopsis

Get the tail element(s) from a list.

Description
  • Return a list consisting of all but the first element of lst.

  • Return a list consisting of the last n elements of lst.

Examples

All but first element:

rascal>import List;
ok
rascal>tail([10,20,30]);
list[int]: [20,30]

Try an error case:

rascal>tail([]);
|std:///List.rsc|(17488,725,<762,0>,<797,57>): EmptyList()
	at *** somewhere ***(|std:///List.rsc|(17488,725,<762,0>,<797,57>))
	at tail(|prompt:///|(5,2,<1,5>,<1,7>))
 
ok

Last n elements:

rascal>tail([10, 20, 30, 40, 50, 60], 3);
list[int]: [40,50,60]

Try an error case:

rascal>tail([10, 20, 30, 40, 50, 60], 10);
|std:///List.rsc|(18216,115,<799,0>,<800,73>): IndexOutOfBounds(4)
	at *** somewhere ***(|std:///List.rsc|(18216,115,<799,0>,<800,73>))
	at tail(|prompt:///|(31,2,<1,31>,<1,33>))
 
ok

1.6.40. take

Function

list[&T] take(int n, list[&T] lst)

Synopsis

Get number of elements from the head of a list.

Description

Get n elements (or size(lst) elements if size(lst) < n) from the head of the list. See drop to remove elements from the head of a list.

Examples
rascal>import List;
ok
rascal>take(2, [3, 1, 4, 5]);
list[int]: [3,1]
rascal>take(6, [3, 1, 4, 5]);
list[int]: [3,1,4,5]
rascal>take(2, ["zebra", "elephant", "snake", "owl"]);
list[str]: ["zebra","elephant"]

1.6.41. takeOneFrom

Function

tuple[&T, list[&T]] takeOneFrom(list[&T] lst)

Synopsis

Remove an arbitrary element from a list, returns the element and the modified list.

Description

Select an arbitrary element from lst, and return a tuple consisting of:

  • the selected element, and

  • a new list consisting of all elements of lst except the selected element.

See getOneFrom to only selected an element from a list.

Examples
rascal>import List;
ok
rascal>takeOneFrom([10,20,30,40,50]);
tuple[int,list[int]]: <50,[10,20,30,40]>
rascal>takeOneFrom([10,20,30,40,50]);
tuple[int,list[int]]: <10,[20,30,40,50]>
rascal>takeOneFrom([10,20,30,40,50]);
tuple[int,list[int]]: <20,[10,30,40,50]>
rascal>takeOneFrom(["zebra", "elephant", "snake", "owl"]);
tuple[str,list[str]]: <"snake",["zebra","elephant","owl"]>
rascal>takeOneFrom(["zebra", "elephant", "snake", "owl"]);
tuple[str,list[str]]: <"zebra",["elephant","snake","owl"]>
rascal>takeOneFrom(["zebra", "elephant", "snake", "owl"]);
tuple[str,list[str]]: <"zebra",["elephant","snake","owl"]>

1.6.42. takeWhile

Function

list[&T] takeWhile(list[&T] lst, bool (&T a) take)

Synopsis

Take elements from the front of the list as long as a predicate is true.

Examples
rascal>import List;
ok
rascal>bool isEven(int a) = a mod 2 == 0;
bool (int): function(|prompt:///|(0,34,<1,0>,<1,34>))
rascal>takeWhile([2,4,6,8,1,2,3,4,5],isEven);
list[int]: [2,4,6,8]

1.6.43. toMap

Function

map[&A,list[&B]] toMap(list[tuple[&A, &B]] lst) throws MultipleKey

Synopsis

Convert a list of pairs to a map; first elements are associated with a set of second elements.

Description

Convert a list of tuples to a map in which the first element of each tuple is associated with the set of second elements from all tuples with the same first element. Keys should be unique.

Examples
rascal>import List;
ok
rascal>toMap([<1,10>, <1, 11>, <2, 20>, <3, 30>, <3, 31>]);
map[int, list[int]]: (
  1:[10,11],
  3:[30,31],
  2:[20]
)
Pitfalls

toMap collects all values in tuples with the same first value in a set. Contrast this with toMapUnique that associates each first tuple value with the second tuple value, but imposes the constraint that those keys are unique.

1.6.44. toMapUnique

Function

map[&A,&B] toMapUnique(list[tuple[&A, &B]] lst) throws MultipleKey

Synopsis

Convert a list of tuples to a map; result must be a map.

Description

Convert a list of tuples to a map; result must be a map.

Examples
rascal>import List;
ok
rascal>toMapUnique([<1,10>, <2, 20>, <3, 30>]);
map[int, int]: (1:10,3:30,2:20)

Let’s explore an error case:

rascal>toMapUnique([<1,10>, <1, 11>, <2, 20>, <3, 30>]);
|std:///List.rsc|(20732,667,<889,0>,<912,79>): MultipleKey(1,10,11)
	at *** somewhere ***(|std:///List.rsc|(20732,667,<889,0>,<912,79>))
	at toMapUnique(|prompt:///|(43,2,<1,43>,<1,45>))
 
ok
Pitfalls

The keys in a map are unique by definition. toMapUnique throws a MultipleKey exception when the list contains more than one tuple with the same first value.

1.6.45. top

Function

&T top(list[&T] lst) throws EmptyList

Synopsis

Take the top element of a list. .Description This function is identical to [head]. Also see pop and push.

Examples
rascal>import List;
ok
rascal>top([3, 1, 4, 5]);
int: 3
rascal>top(["zebra", "elephant", "snake", "owl"]);
str: "zebra"

1.6.46. toRel

Function

rel[&T,&T] toRel(list[&T] lst)

Synopsis

Convert a list to a relation. .Description Convert a list to relation, where each tuple encodes which elements are followed by each other. This function will return an empty relation for empty lists and for singleton lists.

Examples
rascal>import List;
ok
rascal>toRel([3, 1, 4, 5]);
rel[int,int]: {
  <1,4>,
  <3,1>,
  <4,5>
}
rascal>toRel(["zebra", "elephant", "snake", "owl"]);
rel[str,str]: {
  <"snake","owl">,
  <"zebra","elephant">,
  <"elephant","snake">
}

1.6.47. toSet

Function

set[&T] toSet(list[&T] lst)

Synopsis

Convert a list to a set.

Description

Convert lst to a set.

Examples
rascal>import List;
ok
rascal>toSet([10, 20, 30, 40]);
set[int]: {10,40,20,30}
rascal>toSet(["zebra", "elephant", "snake", "owl"]);
set[str]: {"snake","owl","zebra","elephant"}

Note that the same can be done using splicing

rascal>l = [10,20,30,40];
list[int]: [10,20,30,40]
rascal>s = {*l};
set[int]: {10,40,20,30}

1.6.48. toString

Function

str toString(list[&T] lst)

Synopsis

Convert a list to a string.

Description

Convert lst to a string.

Examples
rascal>import List;
ok
rascal>toString([10, 20, 30]);
str: "[10,20,30]"
rascal>toString(["zebra", "elephant", "snake", "owl"]);
str: "[\"zebra\",\"elephant\",\"snake\",\"owl\"]"

1.6.49. itoString

Function

str itoString(list[&T] lst)

Synopsis

Convert a list to an indented string.

Description

Convert lst to a indented string.

Examples
rascal>import List;
ok
rascal>itoString([10, 20, 30]);
str: "[10,20,30]"
rascal>itoString(["zebra", "elephant", "snake", "owl"]);
str: "[\"zebra\",\"elephant\",\"snake\",\"owl\"]"

1.6.50. unzip

Function
  • tuple[list[&T],list[&U]] unzip(list[tuple[&T,&U]] lst)

  • tuple[list[&T],list[&U],list[&V]] unzip(list[tuple[&T,&U,&V]] lst)

Synopsis

Make a pair (triple) of lists from a list of pairs (triples).

Description

Also see unzip;

Examples
rascal>import List;
ok
rascal>unzip([<3,"thirty">, <1,"ten">, <4,"forty">]);
tuple[list[int],list[str]]: <[3,1,4],["thirty","ten","forty"]>
rascal>unzip([<3,"thirty",300>, <1,"ten",100>, <4,"forty",400>]);
tuple[list[int],list[str],list[int]]: <[3,1,4],["thirty","ten","forty"],[300,100,400]>

1.6.51. upTill

Function

list[int] upTill(int n)

Synopsis

Returns the list 0,1..n-1. .Description Returns the list 0, 1, .., n-1, this is slightly faster than [0..n], since the returned values are shared.

Examples
rascal>import List;
ok
rascal>upTill(10);
list[int]: [0,1,2,3,4,5,6,7,8,9]

1.6.52. zip

Function
  • list[tuple[&T first, &U second]] zip(list[&T] a, list[&U] b)

  • list[tuple[&T first, &U second, &V third]] zip(list[&T] a, list[&U] b, list[&V] c)

Synopsis

Make a list of pairs from two (three) lists of the same length.

Description

Also see unzip.

Examples
rascal>import List;
ok
rascal>zip([3, 1, 4], ["thirty", "ten", "forty"]);
lrel[int first,str second]: [
  <3,"thirty">,
  <1,"ten">,
  <4,"forty">
]
rascal>zip([3, 1, 4], ["thirty", "ten", "forty"], [300, 100, 400]);
lrel[int first,str second,int third]: [
  <3,"thirty",300>,
  <1,"ten",100>,
  <4,"forty",400>
]

1.7. ListRelation

Usage

import ListRelation;

Synopsis

Library functions for list relations.

Description

For operators on listrelations see ListRelation in the Rascal Language Reference.

The following functions are defined for list relations :

1.7.1. carrier

Function
  • list[&T] carrier (lrel[&T,&T] R)

  • list[&T] carrier (lrel[&T,&T,&T] R)

  • list[&T] carrier (lrel[&T,&T,&T,&T] R)

  • list[&T] carrier (lrel[&T,&T,&T,&T,&T] R)

Synopsis

Return the list of all elements in any tuple in a list relation.

Examples
rascal>import ListRelation;
ok
rascal>carrier([<1,10>, <2,20>]);
list[int]: [1,10,2,20]
rascal>carrier([<1,10,100,1000>, <2,20,200,2000>]);
list[int]: [1,10,100,1000,2,20,200,2000]

1.7.2. carrierR

Function
  • lrel[&T,&T] carrierR (lrel[&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T] carrierR (lrel[&T,&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T,&T] carrierR (lrel[&T,&T,&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T,&T,&T] carrierR (lrel[&T,&T,&T,&T,&T] R, set[&T] S)

Synopsis

A list relation restricted to certain element values in tuples.

Description

Returns list relation R restricted to tuples with elements in set S.

Examples
rascal>import ListRelation;
ok
rascal>carrierR([<1,10>, <2,20>, <3,30>], {10, 1, 20});
lrel[int,int]: [<1,10>]

1.7.3. carrierX

Function
  • lrel[&T,&T] carrierX (lrel[&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T] carrierX (lrel[&T,&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T,&T] carrierX (lrel[&T,&T,&T,&T] R, set[&T] S)

  • lrel[&T,&T,&T,&T,&T] carrierX (lrel[&T,&T,&T,&T,&T] R, set[&T] S)

Synopsis

A list relation excluding tuples containing certain values.

Description

Returns list relation R excluding tuples with some element in S.

Examples
rascal>import ListRelation;
ok
rascal>carrierX([<1,10>, <2,20>, <3,30>], {10, 1, 20});
lrel[int,int]: [<3,30>]

1.7.4. complement

Function
  • lrel[&T0, &T1] complement(lrel[&T0, &T1] R)

  • lrel[&T0, &T1, &T2] complement(lrel[&T0, &T1, &T2] R)

  • lrel[&T0, &T1, &T2, &T3] complement(lrel[&T0, &T1, &T2, &T3] R)

  • lrel[&T0, &T1, &T2, &T3, &T4] complement(lrel[&T0, &T1, &T2, &T3, &T4] R)

Synopsis

Complement of a list relation.

Description

Given a list relation R a new relation U can be constructed that contains all possible tuples with element values that occur at corresponding tuple positions in R. The function complement returns the complement of R relative to U, in other words: U - R.

Examples
rascal>import ListRelation;
ok

Declare R and compute corresponding U:

rascal>R = [<1,10>, <2, 20>, <3, 30>];
lrel[int,int]: [
  <1,10>,
  <2,20>,
  <3,30>
]
rascal>U = domain® * range®;
lrel[int,int]: [
  <1,10>,
  <1,20>,
  <1,30>,
  <2,10>,
  <2,20>,
  <2,30>,
  <3,10>,
  <3,20>,
  <3,30>
]

Here is the complement of R computed in two ways:

rascal>U - R;
lrel[int,int]: [
  <1,20>,
  <1,30>,
  <2,10>,
  <2,30>,
  <3,10>,
  <3,20>
]
rascal>complement([<1,10>, <2, 20>, <3, 30>]);
lrel[int,int]: [
  <1,20>,
  <1,30>,
  <2,10>,
  <2,30>,
  <3,10>,
  <3,20>
]

1.7.5. domain

Function
  • list[&T0] domain(lrel[&T0,&T1] R)

  • list[&T0] domain(lrel[&T0,&T1,&T2] R)

  • list[&T0] domain(lrel[&T0,&T1,&T2,&T3] R)

  • list[&T0] domain(lrel[&T0,&T1,&T2,&T3,&T4] R)

Synopsis

Domain of a list relation: a list consisting of the first element of each tuple, uniquely.

Description

The domain can be seen as all possible inputs of the relation image operation. The result contains elements (or tuples) in the order of appearance of the original relation, but all occurences after the first occurrence of an element have been removed.

Examples
rascal>import ListRelation;
ok
rascal>domain([<1,10>, <2,20>]);
list[int]: [1,2]
rascal>domain([<"mon", 1>, <"tue", 2>]);
list[str]: ["mon","tue"]

1.7.6. domainR

Function
  • lrel[&T0,&T1] domainR (lrel[&T0,&T1] R, set[&T0] S)

  • lrel[&T0,&T1,&T2] domainR (lrel[&T0,&T1,&T2] R, set[&T0] S)

  • lrel[&T0,&T1,&T2,&T3] domainR (lrel[&T0,&T1,&T2,&T3] R, set[&T0] S)

  • lrel[&T0,&T1,&T2,&T3,&T4] domainR (lrel[&T0,&T1,&T2,&T3,&T4] R, set[&T0] S)

  • lrel[&T0,&T1] domainR (lrel[&T0,&T1] R, list[&T0] L)

  • lrel[&T0,&T1,&T2] domainR (lrel[&T0,&T1,&T2] R, list[&T0] L)

  • lrel[&T0,&T1,&T2,&T3] domainR (lrel[&T0,&T1,&T2,&T3] R, list[&T0] L)

  • lrel[&T0,&T1,&T2,&T3,&T4] domainR (lrel[&T0,&T1,&T2,&T3,&T4] R, list[&T0] L)

Synopsis

List relation restricted to certain domain elements.

Description

Restriction of a list relation R to tuples with first element in S.

Examples
rascal>import ListRelation;
ok
rascal>domainR([<1,10>, <2,20>, <3,30>], {3, 1});
lrel[int,int]: [
  <1,10>,
  <3,30>
]

1.7.7. domainX

Function
  • lrel[&T0,&T1] domainX (lrel[&T0,&T1] R, set[&T0] S)

  • lrel[&T0,&T1,&T2] domainX (lrel[&T0,&T1,&T2] R, set[&T0] S)

  • lrel[&T0,&T1,&T2,&T3] domainX (lrel[&T0,&T1,&T2,&T3] R, set[&T0] S)

  • lrel[&T0,&T1,&T2,&T3,&T4] domainX (lrel[&T0,&T1,&T2,&T3,&T4] R, set[&T0] S)

Synopsis

List relation excluding certain domain values.

Description

List relation R excluding tuples with first element in S.

Examples
rascal>import ListRelation;
ok
rascal>domainX([<1,10>, <2,20>, <3,30>], {3, 1});
lrel[int,int]: [<2,20>]

1.7.8. groupDomainByRange

Function

list[list[&U]] groupDomainByRange(lrel[&U dom, &T ran] input)

Synopsis

Make sets of elements in the domain that relate to the same element in the range.

Examples
rascal>import ListRelation;
ok
rascal>legs = [<"bird", 2>, <"dog", 4>, <"human", 2>, <"spider", 8>, <"millepede", 1000>, <"crab", 8>, <"cat", 4>];
lrel[str,int]: [
  <"bird",2>,
  <"dog",4>,
  <"human",2>,
  <"spider",8>,
  <"millepede",1000>,
  <"crab",8>,
  <"cat",4>
]
rascal>groupDomainByRange(legs);
list[list[str]]: [
  ["bird","human"],
  ["dog","cat"],
  ["spider","crab"],
  ["millepede"]
]

1.7.9. groupRangeByDomain

Function

list[list[&T]] groupRangeByDomain(lrel[&U dom, &T ran] input)

Synopsis

Make sets of elements in the range that relate to the same element in the domain.

Description
rascal>import ListRelation;
ok
rascal>skins = [<"bird", "feather">, <"dog", "fur">, <"tortoise", "shell">, <"human", "skin">, <"fish", "scale">, <"lizard", "scale">, <"crab", "shell">, <"cat", "fur">];
lrel[str,str]: [
  <"bird","feather">,
  <"dog","fur">,
  <"tortoise","shell">,
  <"human","skin">,
  <"fish","scale">,
  <"lizard","scale">,
  <"crab","shell">,
  <"cat","fur">
]
rascal>groupRangeByDomain(skins);
list[list[str]]: [
  ["feather"],
  ["fur"],
  ["shell"],
  ["skin"],
  ["scale"]
]

1.7.10. ident

Function

lrel[&T, &T] ident (list[&T] S)

Synopsis

The identity list relation.

Description

The identity list relation for set S.

Examples
rascal>import ListRelation;
ok
rascal>ident(["mon", "tue", "wed"]);
lrel[str,str]: [
  <"mon","mon">,
  <"tue","tue">,
  <"wed","wed">
]

1.7.11. invert

Function
  • lrel[ &T1,&T0] invert (lrel[&T0,&T1 ] R)

  • lrel[ &T2,&T1,&T0] invert (lrel[&T0,&T1,&T2 ] R)

  • lrel[ &T3,&T2,&T1,&T0] invert (lrel[&T0,&T1,&T2,&T3 ] R)

  • lrel[&T4,&T3,&T2,&T1,&T0] invert (lrel[&T0,&T1,&T2,&T3,&T4] R)

Synopsis

Invert the tuples in a list relation.

Examples
rascal>import ListRelation;
ok
rascal>invert([<1,10>, <2,20>]);
lrel[int,int]: [
  <10,1>,
  <20,2>
]

1.7.12. range

Function
  • list[&T1] range (lrel[&T0,&T1] R)

  • lrel[&T1,&T2] range (lrel[&T0,&T1, &T2] R)

  • lrel[&T1,&T2,&T3] range (lrel[&T0,&T1,&T2,&T3] R)

  • lrel[&T1,&T2,&T3,&T4] range (lrel[&T0,&T1,&T2,&T3,&T4] R)

Synopsis

The range is composed of all but the first element of each tuple of a list relation, uniquely.

Description

The range can be seen as all the elements of in all possible images of the relation. The result contains elements (or tuples) in the order of appearance of the original relation, but all occurences after the first occurrence of an element have been removed.

Examples
rascal>import ListRelation;
ok
rascal>range([<1,10>, <2,20>]);
list[int]: [10,20]
rascal>range([<"mon", 1>, <"tue", 2>]);
list[int]: [1,2]

1.7.13. rangeR

Function
  • lrel[&T0,&T1] rangeR (lrel[&T0,&T1] R, set[&T1] S)

  • lrel[&T0,&T1] rangeR (lrel[&T0,&T1] R, list[&T1] L)

Synopsis

List relation restricted to certain range values.

Description

Restriction of binary list relation R to tuples with second element in set S.

Examples
rascal>import ListRelation;
ok
rascal>rangeR([<1,10>, <2,20>, <3,30>], {30, 10});
lrel[int,int]: [
  <1,10>,
  <3,30>
]

1.7.14. rangeX

Function
  • lrel[&T0,&T1] rangeX (lrel[&T0,&T1] R, set[&T1] S)

  • lrel[&T0,&T1] rangeX (lrel[&T0,&T1] R, list[&T1] S)

Synopsis

List relation excluding certain range values.

Description

Restriction of binary list relation R to tuples with second element not in set S.

Examples
rascal>import ListRelation;
ok
rascal>rangeX([<1,10>, <2,20>, <3,30>], {30, 10});
lrel[int,int]: [<2,20>]

1.7.15. index

Function

map[&K, set[&V]] index(lrel[&K, &V] R)

Synopsis

Listes a binary list relation as a map

Description

Converts a binary list relation to a map of the domain to a set of the range.

Examples
rascal>import ListRelation;
ok
rascal>index([<1,10>, <2,20>, <3,30>, <30,10>]);
map[int, set[int]]: (
  1:{10},
  3:{30},
  2:{20},
  30:{10}
)

1.7.16. squeeze

Function

list[&T] squeeze(list[&T] xs)

1.8. Location

Usage

import Location;

Synopsis

Library functions for source locations.

Description

For a description of source locations see Location in the Rascal Language Reference.

The following functions are defined for source locations:

  • isSameFile: Check that two locations refer to the same file

  • isLexicallyLess: Compare two location values lexicographically.

  • getContent: Get the textual content a location refers to

  • isStrictlyContainedIn: Is a location textually (strictly) contained in another location?

  • isContainedIn: Is a location textually contained in another location?

  • beginsBefore: Begins a location’s text before (but may overlap with) another location’s text

  • isBefore: Begins and ends a location’s text before another location’s text?

  • isImmediatelyBefore: Occurs a location’s text immediately before another location’s text?

  • beginsAfter: Begins a location’s text after (but may overlap with) another location’s text?

  • isAfter: Is a location’s text completely after another location’s text

  • isImmediatelyAfter: Is a location’s text immediately after another location’s text

  • isOverlapping: Refer two locations to text that overlaps

  • cover: Compute a location that textually covers the text of a list of locations.

A source location l refers to a text fragment in another file or resource. To ease the description we will talk about `l` 's text instead of the text l refers to.

1.8.1. isSameFile

Function

bool isSameFile(loc l, loc r)

Synopsis

Check that two locations refer to the same file.

1.8.2. isLexicallyLess

Function

bool isLexicallyLess(loc l, loc r)

Synopsis

Compare two location values lexicographically.

Description

When the two locations refer to different files, their paths are compared as string. When they refer to the same file, their offsets are compared when present.

Pittfalls

This ordering regards the location value itself as opposed to the text it refers to.

1.8.3. getContent

Function

str getContent(loc l)

Synopsis

Get the textual content a location refers to.

1.8.4. isStrictlyContainedIn

Function

bool isStrictlyContainedIn(loc inner, loc outer)

Synopsis

Is a location textually (strictly) contained in another location?

Description

Strict containment between two locations inner and outer holds when

  • outer 's text begins before inner 's text, or

  • outer 's text ends after inner 's text, or

  • both.

1.8.5. isContainedIn

Function

bool isContainedIn(loc inner, loc outer)

Synopsis

Is a location textually contained in another location?

Description

Containment between two locations inner and outer holds when

  • inner and outer are equal, or

  • inner is strictly contained in outer.

1.8.6. beginsBefore

Function

bool beginsBefore(loc l, loc r)

Synopsis

Begins a location’s text before (but may overlap with) another location’s text?

1.8.7. isBefore

Function

bool isBefore(loc l, loc r)

Synopsis

Begins and ends a location’s text before another location’s text?

Description

isBefore(l, r) holds when l 's text occurs textually before r 's text.

1.8.8. isImmediatelyBefore

Function

bool isImmediatelyBefore(loc l, loc r)

Synopsis

Occurs a location’s text immediately before another location’s text?

Description

isImmediatelyBefore(l, r) holds when l 's text occurs textually before, and is adjacent to, r 's text.

1.8.9. beginsAfter

Function

bool beginsAfter(loc l, loc r)

Synopsis

Begins a location’s text after (but may overlap with) another location’s text?

Description beginsAfter(l, r) holds when l 's text begins after r 's text. No assumption is made about the end of both texts. In other words, l 's text may end before or after the end of r 's text.

1.8.10. isAfter

Function

bool isAfter(loc l, loc r)

Synopsis

Is a location’s text completely after another location’s text?

1.8.11. isImmediatelyAfter

Function

bool isImmediatelyAfter(loc l, loc r)

Synopsis

Is a location’s text immediately after another location’s text?

1.8.12. isOverlapping

Function

bool isOverlapping(loc l, loc r)

Synopsis

Refer two locations to text that overlaps?

1.8.13. cover

Function

loc cover(list[loc] locs)

Synopsis

Compute a location that textually covers the text of a list of locations.

Description

Create a new location that refers to the smallest text area that overlaps with the text of the given locations. The given locations should all refer to the same file but they may be overlapping or be contained in each other.

1.9. Map

Usage

import Map;

Synopsis

Library functions for maps.

Description

For operators on maps see Map in the Rascal Language Reference.

The following functions are defined for maps:

  • delete: Delete a key from a map.

  • domain: Determine the domain (set of keys) of a map.

  • domainR: Map restricted to certain keys.

  • domainX: Map with certain keys excluded.

  • getOneFrom: Get a n arbitrary key from a map.

  • invert: Invert the (key,value) pairs in a map.

  • invertUnique: Invert the (key,value) pairs in a map.

  • isEmpty: Test whether a map is empty.

  • mapper: Apply a function to all (key, value) pairs in a map.

  • range: The range (set of values that correspond to its keys) of a map.

  • rangeR: Map restricted to certain values in (key,values) pairs.

  • rangeX: Map with certain values in (key,value) pairs excluded.

  • size: Number of (key, value) pairs in a map.

  • toList: Convert a map to a list of tuples.

  • toRel: Convert a map to a relation.

  • toRel:

  • toRel:

  • toString: Convert a map to a string.

  • itoString: Convert a map to a indented string.

1.9.1. delete

Function

map[&K,&V] delete(map[&K,&V] m, &K k)

Synopsis

Delete a key from a map.

Description

Returns the map m minus the key k.

Examples
rascal>import Map;
ok
rascal>delete(("apple":1,"pear":2), "apple");
map[str, int]: ("pear":2)

1.9.2. domain

Function

set[&K] domain(map[&K, &V] M)

Synopsis

Determine the domain (set of keys) of a map.

Description

Returns the domain (set of keys) of map M.

Examples
rascal>import Map;
ok
rascal>domain"apple": 1, "pear": 2;
set[str]: {"pear","apple"}

1.9.3. domainR

Function

map[&K, &V] domainR(map[&K, &V] M, set[&K] S)

Synopsis

Map restricted to certain keys.

Description

Return the map M restricted to pairs with key in S.

Examples
rascal>import Map;
ok
rascal>domainR(("apple": 1, "pear": 2, "orange": 3), {"apple", "pear"});
map[str, int]: ("pear":2,"apple":1)

1.9.4. domainX

Function

map[&K, &V] domainX(map[&K, &V] M, set[&K] S)

Synopsis

Map with certain keys excluded.

Description

Return the map M restricted to pairs with key not in S.

Examples
rascal>import Map;
ok
rascal>domainX(("apple": 1, "pear": 2, "orange": 3), {"apple", "pear"});
map[str, int]: ("orange":3)

1.9.5. getOneFrom

Function

&K getOneFrom(map[&K, &V] M)

Synopsis

Get a n arbitrary key from a map.

Description

Returns an arbitrary key of map M.

Examples
rascal>import Map;
ok
rascal>getOneFrom"apple": 1, "pear": 2, "pineapple": 3;
str: "pineapple"
rascal>getOneFrom"apple": 1, "pear": 2, "pineapple": 3;
str: "apple"
rascal>getOneFrom"apple": 1, "pear": 2, "pineapple": 3;
str: "pineapple"

1.9.6. invert

Function

map[&V, set[&K]] invert(map[&K, &V] M)

Synopsis

Invert the (key,value) pairs in a map.

Description

Returns inverted map in which each value in the old map M is associated with a set of key values from the old map. Also see invertUnique.

Examples
rascal>import Map;
ok
rascal>invert"apple": 1, "pear": 2, "orange": 1;
map[int, set[str]]: (
  1:{"orange","apple"},
  2:{"pear"}
)

1.9.7. invertUnique

Function

map[&V, &K] invertUnique(map[&K, &V] M)

Synopsis

Invert the (key,value) pairs in a map.

Description

Returns a map with key and value inverted; the result should be a map. If the initial map contains duplicate values, the MultipleKey exception is raised since an attempt is made to create a map where more than one value would be associated with the same key.

Also see invert and Exception.

Examples
rascal>import Map;
ok
rascal>invertUnique"apple": 1, "pear": 2, "orange": 3;
map[int, str]: (1:"apple",3:"orange",2:"pear")

Here is an examples that generates an exception:

rascal>invertUnique"apple": 1, "pear": 2, "orange": 1;
|std:///Map.rsc|(2833,742,<131,0>,<157,54>): MultipleKey(1,"apple","orange")
	at *** somewhere ***(|std:///Map.rsc|(2833,742,<131,0>,<157,54>))
	at invertUnique(|prompt:///|(47,1,<1,47>,<1,48>))
 
ok

1.9.8. isEmpty

Function

bool isEmpty(map[&K, &V] M)

Synopsis

Test whether a map is empty.

Description

Returns true if map M is empty, and false otherwise.

Examples
rascal>import Map;
ok
rascal>isEmpty)); bool: true rascal>isEmpty(("apple": 1, "pear": 2, "orange": 3;
bool: false

1.9.9. mapper

Function

map[&K, &V] mapper(map[&K, &V] M, &L (&K) F, &W (&V) G)

Synopsis

Apply a function to all (key, value) pairs in a map.

Description

Apply the functions F and G to each key/value pair in a map and return the transformed map.

Examples
rascal>import Map;
ok
rascal>str prefix(str s) { return "X" + s; }
str (str): function(|prompt:///|(0,37,<1,0>,<1,37>))
rascal>int incr(int x) { return x + 1; }
int (int): function(|prompt:///|(0,33,<1,0>,<1,33>))
rascal>mapper(("apple": 1, "pear": 2, "orange": 3), prefix, incr);
map[str, int]: ("Xapple":2,"Xorange":4,"Xpear":3)

1.9.10. range

Function

set[&V] range(map[&K, &V] M)

Synopsis

The range (set of values that correspond to its keys) of a map.

Description

Returns the range (set of values) of map M.

Examples
rascal>import Map;
ok
rascal>range"apple": 1, "pear": 2;
set[int]: {1,2}

1.9.11. rangeR

Function

map[&K, &V] rangeR(map[&K, &V] M, set[&V] S)

Synopsis

Map restricted to certain values in (key,values) pairs.

Description

Returns the map restricted to pairs with values in S.

Examples
rascal>import Map;
ok
rascal>rangeR(("apple": 1, "pear": 2, "orange": 3), {2, 3});
map[str, int]: ("pear":2,"orange":3)

1.9.12. rangeX

Function

map[&K, &V] rangeX(map[&K, &V] M, set[&V] S)

Synopsis

Map with certain values in (key,value) pairs excluded.

Description

Returns the map restricted to pairs with values not in S.

Examples
rascal>import Map;
ok
rascal>rangeX(("apple": 1, "pear": 2, "orange": 3), {2, 3});
map[str, int]: ("apple":1)

1.9.13. size

Function

int size(map[&K, &V] M)

Synopsis

Number of (key, value) pairs in a map.

Description

Returns the number of pairs in map M.

Examples
rascal>import Map;
ok
rascal>size"apple": 1, "pear": 2, "orange": 3;
int: 3

1.9.14. toList

Function

list[tuple[&K, &V]] toList(map[&K, &V] M)

Synopsis

Convert a map to a list of tuples.

Examples
rascal>import Map;
ok
rascal>toList"apple": 1, "pear": 2, "orange": 3;
lrel[str,int]: [
  <"apple",1>,
  <"orange",3>,
  <"pear",2>
]

1.9.15. toRel

Function
  • rel[&K,&V] toRel(map[&K,set[&V]] M)

  • rel[&K,&V] toRel(map[&K,list[&V]] M)

  • default java rel[&K, &V] toRel(map[&K, &V] M)

Synopsis

Convert a map to a relation.

Examples
rascal>import Map;
ok
rascal>toRel"apple": 1, "pear": 2, "orange": 3;
rel[str,int]: {
  <"pear",2>,
  <"orange",3>,
  <"apple",1>
}

1.9.16. toString

Function

str toString(map[&K, &V] M)

Synopsis

Convert a map to a string.

Examples
rascal>import Map;
ok
rascal>toString"apple": 1, "pear": 2, "orange": 3;
str: "(\"pear\":2,\"orange\":3,\"apple\":1)"

1.9.17. itoString

Function

str itoString(map[&K, &V] M)

Synopsis

Convert a map to a indented string.

Examples
rascal>import Map;
ok
rascal>itoString"apple": 1, "pear": 2, "orange": 3;
str: "(\"pear\":2,\"orange\":3,\"apple\":1)"

1.10. Message

Usage

import Message;

Synopsis

A Message datatype that represents messages in the IDE.

Types
data Message = error(str msg, loc at)
             | warning(str msg, loc at)
             | info(str msg, loc at);
Description

Messages can be used to communicate information about source texts. They can be interpreted by IDEs to display type errors and warnings, etc. Message s are, for instance, used as annotations of algebraic data type. A very common example is to annotate parse trees with messages.

1.10.1. Message

Types
data Message
     = error(str msg, loc at)
     | error(str msg)
     | warning(str msg, loc at)
     | info(str msg, loc at)
     ;
Description

Messages can be used to communicate information about source texts. They can be interpreted by IDE’s to display type errors and warnings, etc.

1.11. Node

Usage

import Node;

Synopsis

Library functions for nodes.

Description

For operators on nodes see Node in the Rascal Language Reference.

The following functions are defined for nodes:

  • arity: Determine the number of children of a node.

  • delAnnotation: Delete a specific annotation from a node.

  • delAnnotations: Delete all annotations from a node.

  • delAnnotationsRec: Delete recursively all annotations from all nodes in a value.

  • getAnnotations:

  • getChildren: Get the children of a node.

  • getKeywordParameters: Get the keyword parameters of a node.

  • setKeywordParameters: Set the keyword parameters of a node.

  • getName: Determine the name of a node.

  • makeNode: Create a node given its function name and arguments.

  • setAnnotations: Add a map of annotations to a node value.

  • unset: Reset a specific keyword parameter back to their default on a node

  • unset: Reset a set of keyword parameters back to their default on a node

  • unset: Reset all keyword parameters back to their default

  • unsetRec: Recursively reset all keyword parameters of the node and its children back to their default

  • unsetRec: Recursively reset a specific keyword parameter of the node and its children back to its default

  • unsetRec: Recursively reset a selected set of keyword parameters of the node and its children back to their default

  • arbNode:

  • toString: Convert a node to a string.

  • itoString: Convert a node to an indented string.

1.11.1. arity

Function

int arity(node T)

Synopsis

Determine the number of children of a node.

Examples
rascal>import Node;
ok
rascal>arity("f"(10, "abc"));
int: 2
rascal>arity("f"(10, "abc", false));
int: 3

1.11.2. delAnnotation

Function

&T <: node delAnnotation(&T <: node x, str label)

Synopsis

Delete a specific annotation from a node.

Examples
rascal>import Node;
ok
rascal>F = setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
  @size="large",
  @color="red"
]
rascal>delAnnotation(F, "size");
node: "f"(10,"abc")[
  @color="red"
]

1.11.3. delAnnotations

Function

&T <: node delAnnotations(&T <: node x)

Synopsis

Delete all annotations from a node.

Examples
rascal>import Node;
ok
rascal>F = setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
  @size="large",
  @color="red"
]
rascal>delAnnotations(F);
node: "f"(10,"abc")

1.11.4. delAnnotationsRec

Function

&T delAnnotationsRec(&T v)

Synopsis

Delete recursively all annotations from all nodes in a value.

Examples
rascal>import Node;
ok
rascal>G = setAnnotations("g"("def"), ("level" : "20", "direction" : "north"));
node: "g"("def")[
  @level="20",
  @direction="north"
]
rascal>F = setAnnotations("f"(10, G), ("color" : "red", "size" : "large"));
node: "f"(
  10,
  "g"("def")[
    @level="20",
    @direction="north"
  ])[
  @size="large",
  @color="red"
]
rascal>delAnnotationsRec(F);
node: "f"(
  10,
  "g"("def"))

1.11.5. getAnnotations

Function

map[str,value] getAnnotations(node x)

Synopsis

Retrieve the annotations of a node value as a map. Annotations are deprecated.

1.11.6. getChildren

Function

list[value] getChildren(node T)

Synopsis

Get the children of a node.

Examples
rascal>import Node;
ok
rascal>getChildren("f"(10, "abc"));
list[value]: [10,"abc"]

1.11.7. getKeywordParameters

Function

map[str,value] getKeywordParameters(node T)

Synopsis

Get the keyword parameters of a node.

Examples
rascal>import Node;
ok
rascal>getKeywordParameters("f"(10, "abc", height=0));
map[str, value]: ("height":0)

1.11.8. setKeywordParameters

Function

&T <: node setKeywordParameters(&T <: node x, map[str,value] keywordParameters)

Synopsis

Set the keyword parameters of a node.

Examples
rascal>import Node;
ok
rascal>setKeywordParameters("f"(10, "abc"), ("height":0));
node: "f"(10,"abc",
  height=0)

1.11.9. getName

Function

str getName(node T)

Synopsis

Determine the name of a node.

Examples
rascal>import Node;
ok
rascal>getName("f"(10, "abc"));
str: "f"

1.11.10. makeNode

Function

node makeNode(str N, value V…​, map[str, value] keywordParameters = ())

Synopsis

Create a node given its function name and arguments.

Examples
rascal>import Node;
ok
rascal>makeNode("f", [10, "abc"]);
node: "f"(10,"abc")

1.11.11. setAnnotations

Function

&T <: node setAnnotations(&T <: node x, map[str, value] annotations)

Synopsis

Add a map of annotations to a node value.

Description

Set the annotations on node value x as described by the map annotations.

Examples
rascal>import Node;
ok
rascal>setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
  @size="large",
  @color="red"
]
Pitfalls

This function may result in run-time type errors later if you store a value with a label that has an incomparable annotation type declared.

1.11.12. unset

Function
  • &T <: node unset(&T <: node x, str keywordParameter)

  • &T <: node unset(&T <: node x, set[str] keywordParameters)

  • &T <: node unset(&T <: node x)

Synopsis

Reset a specific keyword parameter back to their default on a node.

1.11.13. unsetRec

Function
  • &T <: node unsetRec(&T <: node x)

  • &T <: node unsetRec(&T <: node x, str keywordParameter)

  • &T <: node unsetRec(&T <: node x, set[str] keywordParameters)

Synopsis

Recursively reset all keyword parameters of the node and its children back to their default.

1.11.14. arbNode

Function

node arbNode()

1.11.15. toString

Function

str toString(node T)

Synopsis

Convert a node to a string.

Examples
rascal>import Node;
ok
rascal>F = setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
  @size="large",
  @color="red"
]
rascal>toString(F);
str: "\"f\"(10,\"abc\")[@size=\"large\",@color=\"red\"]"

1.11.16. itoString

Function

str itoString(node T)

Synopsis

Convert a node to an indented string.

Examples
rascal>import Node;
ok
rascal>F = setAnnotations("f"(10, "abc"), ("color" : "red", "size" : "large"));
node: "f"(10,"abc")[
  @size="large",
  @color="red"
]
rascal>itoString(F);
str: "\"f\"(10,\"abc\")[\n  @size=\"large\",\n  @color=\"red\"\n]"

1.12. ParseTree

Usage

import ParseTree;

Synopsis

Library functions for parse trees.

Description

A concrete syntax tree or parse tree is an ordered, rooted tree that represents the syntactic structure of a string according to some formal grammar.

Most Rascal users will encounter parse trees in the form of concrete values. Expert users may find the detailed description here useful when writing generic functions on parse trees.

In Rascal parse trees, the interior nodes are labeled by rules of the grammar, while the leaf nodes are labeled by terminals (characters) of the grammar.

Tree is the universal parse tree data type in Rascal and can be used to represent parse trees for any language.

  • Tree is a subtype of the type node.

  • All types (non-terminals) declared in syntax definitions are sub-types of Tree.

  • All concrete syntax expressions produce parse trees with a type corresponding to a non-terminals.

  • Trees can be annotated in various ways, see features for IDE construction. Most importantly the \loc annotation always points to the source location of any (sub) parse tree.

Parse trees are usually analyzed and constructed using concrete syntax expressions and concrete syntax patterns.

Advanced users may want to create tools that analyze any parse tree, regardless of the syntax definition that generated it, you can manipulate them on the abstract level.

A parse tree is of type Tree using the auxiliary types Production, Symbol, Condition, Attr, Associativity, CharRange. Effectively, a parse tree is a nested tree structure of type Tree.

  • Most internal nodes are applications (appl) of a Production to a list of children Tree nodes. Production is the abstract representation of a rule in a syntax definition, which consists of a definition of an alternative for a Symbol by a list of Symbols.

  • The leaves of a parse tree are always characters (char), which have an integer index in the UTF8 table.

  • Some internal nodes encode ambiguity (amb) by pointing to a set of alternative Tree nodes.

The Production and Symbol types are an abstract notation for rules in syntax definitions, while the Tree type is the actual notation for parse trees.

Parse trees are called parse forests when they contain amb nodes.

You can analyze and manipulate parse trees in three ways:

The type of a parse tree is the symbol that it’s production produces, i.e. appl(prod(sort("A"),[],{}),[]) has type A. Ambiguity nodes Each such a non-terminal type has Tree as its immediate super-type.

Examples
rascal>import ParseTree;
ok
rascal>syntax A = "a";
ok

will make the following succeed:

rascal>parse(#A,"a") ==
>>>>>>>appl(
>>>>>>>  prod(
>>>>>>>    sort("A"),
>>>>>>>    [lit("a")],
>>>>>>>    {}),
>>>>>>>  [appl(
>>>>>>>      prod(
>>>>>>>        lit("a"),
>>>>>>>        [\char-class([range(97,97)])],
>>>>>>>        {}),
>>>>>>>      [char(97)])]);
bool: false

You see that the defined non-terminal A ends up as the production for the outermost node. As the only child is the tree for recognizing the literal a, which is defined to be a single a from the character-class [ a ].

When we use labels in the definitions, they also end up in the trees. The following definition

rascal>import ParseTree;
ok
rascal>lexical B= myB:"b";
ok
rascal>lexical C = myC:"c" B bLabel;
ok

Will make the following succeed:

rascal>parse(#C,"cb") ==
>>>>>>>appl(
>>>>>>>  prod(
>>>>>>>    label(
>>>>>>>      "myC",
>>>>>>>      lex("C")),
>>>>>>>    [
>>>>>>>      lit("c"),
>>>>>>>      label(
>>>>>>>        "bLabel",
>>>>>>>        lex("B"))
>>>>>>>    ],
>>>>>>>    {}),
>>>>>>>  [appl(
>>>>>>>      prod(
>>>>>>>        lit("c"),
>>>>>>>        [\char-class([range(99,99)])],
>>>>>>>        {}),
>>>>>>>      [char(99)]),appl(
>>>>>>>      prod(
>>>>>>>        label(
>>>>>>>          "myB",
>>>>>>>          lex("B")),
>>>>>>>        [lit("b")],
>>>>>>>        {}),
>>>>>>>      [appl(
>>>>>>>          prod(
>>>>>>>            lit("b"),
>>>>>>>            [\char-class([range(98,98)])],
>>>>>>>            {}),
>>>>>>>          [char(98)])])]);
bool: false

Here you see that the alternative name is a label around the first argument of prod while argument labels become labels in the list of children of a prod.

Pitfalls

For historical reasons the name of the annotation is "loc" and this interferes with the Rascal keyword loc for the type of source locations. Therefore the annotation name has to be escaped as \loc when it is declared or used.

The following functions and data types are declared for ParseTrees:

1.12.1. Tree

Types
data Tree
     = appl(Production prod, list[Tree] args)
     | cycle(Symbol symbol, int cycleLength)
     | amb(set[Tree] alternatives)
     | char(int character)
     ;
Synopsis

The Tree data type as produced by the parser.

Description

A Tree defines the trees normally found after parsing; additional constructors exist for execptional cases:

1 Parse tree constructor when parse succeeded.
2 Cyclic parsetree.
3 Ambiguous subtree.
4 A single character.

1.12.2. Production

Types
data Production
     = prod(Symbol def, list[Symbol] symbols, set[Attr] attributes)
     | regular(Symbol def)
     | error(Production prod, int dot)
     | skipped()
     ;
Synopsis

Production in ParseTrees

Description

The type Production is introduced in Type, see Production. Here we extend it with the symbols that can occur in a ParseTree. We also extend productions with basic combinators allowing to construct ordered and un-ordered compositions, and associativity groups.

1 A prod is a rule of a grammar, with a defined non-terminal, a list of terminal and/or non-terminal symbols and a possibly empty set of attributes.
2 A regular is a regular expression, i.e. a repeated construct.
3 A error represents a parse error.
4 A skipped represents skipped input during error recovery.
5 priority means operator precedence, where the order of the list indicates the binding strength of each rule;
6 assoc means all alternatives are acceptable, but nested on the declared side;
7 reference means a reference to another production rule which should be substituted there, for extending priority chains and such.

1.12.3. Production

Types
data Production
     = \priority(Symbol def, list[Production] choices)
     | \associativity(Symbol def, Associativity \assoc, set[Production] alternatives)
     | \reference(Symbol def, str cons)
     ;

1.12.4. Attr

Types
data Attr
     = \bracket()
     | \assoc(Associativity \assoc)
     ;
Synopsis

Attributes in productions.

Description

An Attr (attribute) documents additional semantics of a production rule. Neither tags nor brackets are processed by the parser generator. Rather downstream processors are activated by these. Associativity is a parser generator feature though.

1.12.5. Associativity

Types
data Associativity
     = \left()
     | \right()
     | \assoc()
     | \non-assoc()
     ;
Synopsis

Associativity attribute.

Description

Associativity defines the various kinds of associativity of a specific production.

1.12.6. CharRange

Types
data CharRange
     = range(int begin, int end)
     ;
Synopsis

Character ranges and character class .Description

  • CharRange defines a range of characters.

  • A CharClass consists of a list of characters ranges.

1.12.7. CharClass

Types

list[CharRange]

1.12.8. Symbol

Types
data Symbol
     = \start(Symbol symbol)
     ;
Synopsis

Symbols that can occur in a ParseTree

Description

The type Symbol is introduced in Type, see Symbol, to represent the basic Rascal types, e.g., int, list, and rel. Here we extend it with the symbols that may occur in a ParseTree.

1 The start symbol wraps any symbol to indicate that it is a start symbol of the grammar and may occur at the root of a parse tree.
2 Context-free non-terminal
3 Lexical non-terminal
4 Layout symbols
5 Terminal symbols that are keywords
6 Parameterized context-free non-terminal
7 Parameterized lexical non-terminal
8 Terminal.
9 Case-insensitive terminal.
10 Character class
11 Empty symbol
12 Optional symbol
13 List of one or more symbols without separators
14 List of zero or more symbols without separators
15 List of one or more symbols with separators
16 List of zero or more symbols with separators
17 Alternative of symbols
18 Sequence of symbols
19 Conditional occurrence of a symbol.

1.12.9. Symbol

Types
data Symbol
     = \sort(str name)
     | \lex(str name)
     | \layouts(str name)
     | \keywords(str name)
     | \parameterized-sort(str name, list[Symbol] parameters)
     | \parameterized-lex(str name, list[Symbol] parameters)
     ;

1.12.10. Symbol

Types
data Symbol
     = \lit(str string)
     | \cilit(str string)
     | \char-class(list[CharRange] ranges)
     ;

1.12.11. Symbol

Types
data Symbol
     = \empty()
     | \opt(Symbol symbol)
     | \iter(Symbol symbol)
     | \iter-star(Symbol symbol)
     | \iter-seps(Symbol symbol, list[Symbol] separators)
     | \iter-star-seps(Symbol symbol, list[Symbol] separators)
     | \alt(set[Symbol] alternatives)
     | \seq(list[Symbol] symbols)
     ;

1.12.12. Symbol

Types
data Symbol
     = \conditional(Symbol symbol, set[Condition] conditions)
     ;

1.12.13. subtype

Function

bool subtype(Symbol::\sort(_), Symbol::\adt("Tree", _))

1.12.14. Condition

Types
data Condition
     = \follow(Symbol symbol)
     | \not-follow(Symbol symbol)
     | \precede(Symbol symbol)
     | \not-precede(Symbol symbol)
     | \delete(Symbol symbol)
     | \at-column(int column)
     | \begin-of-line()
     | \end-of-line()
     | \except(str label)
     ;
Synopsis

Datatype for declaring preconditions and postconditions on symbols

Description

A Condition can be attached to a symbol; it restricts the applicability of that symbol while parsing input text. For instance, follow requires that it is followed by another symbol and at-column requires that it occurs at a certain position in the current line of the input text.

1.12.15. priority

Function

Production priority(Symbol s, [*Production a, priority(Symbol _, list[Production] b), *Production c])

Synopsis

Nested priority is flattened.

1.12.16. associativity

Function
  • Production associativity(Symbol s, Associativity as, {*Production a, choice(Symbol t, set[Production] b)})

  • Production associativity(Symbol rhs, Associativity a, {associativity(rhs, Associativity b, set[Production] alts), *Production rest})

  • Production associativity(Symbol s, Associativity as, {*Production a, priority(Symbol t, list[Production] b)})

  • Production associativity(Symbol rhs, Associativity a, set[Production] rest)

Synopsis

Normalization of associativity.

Description
  • Choice (see the choice constructor in [Type-ParseTree]) under associativity is flattened.

  • Nested (equal) associativity is flattened.

  • Priority under an associativity group defaults to choice.

1.12.17. parse

Function
  • &T<:Tree parse(type[&T<:Tree] begin, str input, bool allowAmbiguity=false, bool hasSideEffects=false)

  • &T<:Tree parse(type[&T<:Tree] begin, str input, loc origin, bool allowAmbiguity=false, bool hasSideEffects=false)

  • &T<:Tree parse(type[&T<:Tree] begin, loc input, bool allowAmbiguity=false, bool hasSideEffects=false)

Synopsis

Parse input text (from a string or a location) and return a parse tree.

Description
  • Parse a string and return a parse tree.

  • Parse a string and return a parse tree, origin defines the original location of the input.

  • Parse the contents of resource input and return a parse tree.

The parse either throws ParseError exceptions or returns parse trees of type Tree. See .

The allowAmbiguity flag dictates the behavior of the parser in the case of ambiguity. When allowAmbiguity=true the parser will construct ambiguity clusters (local sets of parse trees where the input string is ambiguous). If it is false the parser will throw an Ambiguous exception instead which is comparable to a ParseError exception. The latter option terminates faster.

The hasSideEffects flag is normally set to false. When a uses side-effects to filter ambiguity, this option must be set to true to ensure correct behavior. Otherwise the parser employs optimizations which assume the parse tree construction algorithm is context-free. When filter functions associated with syntax definitions exist that use global variables, for example to store type definitions in a symbol table , then this option must be set to true.

Examples
rascal>import demo::lang::Exp::Concrete::NoLayout::Syntax;
ok
rascal>import ParseTree;
ok

Seeing that parse returns a parse tree:

rascal>parse(#Exp, "2+3");
Exp: (Exp) `2+3`

Catching a parse error:

rascal>import IO;
ok
rascal>try {
>>>>>>>  Exp e = parse(#Exp, "2@3");
>>>>>>>}
>>>>>>>catch ParseError(loc l): {
>>>>>>>  println("I found a parse error at line <l.begin.line>, column <l.begin.column>");
>>>>>>>}
I found a parse error at line 1, column 1
ok

1.12.18. firstAmbiguity

Function
  • Tree firstAmbiguity(type[&T<:Tree] begin, str input)

  • Tree firstAmbiguity(type[&T<:Tree] begin, loc input)

Description

This function is similar to the function in its functionality. However, in case of serious ambiguity parse could be very slow. This function is much faster, because it does not try to construct an entire forest and thus avoids the cost of constructing nested ambiguity clusters.

If the input sentence is not ambiguous after all, simply the entire tree is returned.

1.12.19. unparse

Function

str unparse(Tree tree)

Synopsis

Yield the string of characters that form the leafs of the given parse tree.

Description

unparse is the inverse function of parse, i.e., for every syntactically correct string TXT of type S, the following holds:

unparse(parse(#S, TXT)) == TXT
Examples
rascal>import demo::lang::Exp::Concrete::NoLayout::Syntax;
ok
rascal>import ParseTree;
ok

First parse an expression, this results in a parse tree. Then unparse this parse tree:

rascal>unparse(parse(#Exp, "2+3"));
str: "2+3"

1.12.20. printSymbol

Function

str printSymbol(Symbol sym, bool withLayout)

1.12.21. implode

Function

&T<:value implode(type[&T<:value] t, Tree tree)

Synopsis

Implode a parse tree according to a given (ADT) type.

Description

Given a grammar for a language, its sentences can be parsed and the result is a parse tree (or more precisely a value of type Tree). For many applications this is sufficient and the results are achieved by traversing and matching them using concrete patterns.

In other cases, the further processing of parse trees is better done in a more abstract form. The abstract syntax for a language is a data type that is used to represent programs in the language in an abstract form. Abstract syntax has the following properties:

  • It is "abstract" in the sense that it does not contain textual details such as parentheses, layout, and the like.

  • While a language has one grammar (also known as, concrete syntax) it may have several abstract syntaxes for different purposes: type analysis, code generation, etc.

The function implode bridges the gap between parse tree and abstract syntax tree. Given a parse tree and a Rascal type it traverses them simultaneously and constructs an abstract syntax tree (a value of the given type) as follows:

  • Literals, layout and empty (i.e. ()) nodes are skipped.

  • Regular */+ lists are imploded to `list`s or `set`s depending on what is expected in the ADT.

  • Ambiguities are imploded to `set`s.

  • If the expected type is str the tree is unparsed into a string. This happens for both lexical and context-free parse trees.

  • If a tree’s production has no label and a single AST (i.e. non-layout, non-literal) argument (for instance, an injection), the tree node is skipped, and implosion continues with the lone argument. The same applies to bracket productions, even if they are labeled.

  • If a tree’s production has no label, but more than one argument, the tree is imploded to a tuple (provided this conforms to the ADT).

  • Optionals are imploded to booleans if this is expected in the ADT. This also works for optional literals, as shown in the example below.

  • An optional is imploded to a list with zero or one argument, iff a list type is expected.

  • If the argument of an optional tree has a production with no label, containing a single list, then this list is spliced into the optional list.

  • For trees with (cons-)labeled productions, the corresponding constructor in the ADT corresponding to the non-terminal of the production is found in order to make the AST.

  • If the provided type is node, (cons-)labeled trees will be imploded to untyped `node`s. This means that any subtrees below it will be untyped nodes (if there is a label), tuples of nodes (if a label is absent), and strings for lexicals.

  • Unlabeled lexicals are imploded to str, int, real, bool depending on the expected type in the ADT. To implode lexical into types other than str, the PDB parse functions for integers and doubles are used. Boolean lexicals should match "true" or "false". NB: lexicals are imploded this way, even if they are ambiguous.

  • If a lexical tree has a cons label, the tree imploded to a constructor with that name and a single string-valued argument containing the tree’s yield.

An IllegalArgument exception is thrown if during implosion a tree is encountered that cannot be imploded to the expected type in the ADT. As explained above, this function assumes that the ADT type names correspond to syntax non-terminal names, and constructor names correspond to production labels. Labels of production arguments do not have to match with labels in ADT constructors.

Finally, source location annotations are propagated as annotations on constructor ASTs. To access them, the user is required to explicitly declare a location annotation on all ADTs used in implosion. In other words, for every ADT type T, add:

anno loc T@location;
Examples

Here are some examples for the above rules.

Example for rule 5

Given the grammar

syntax IDTYPE = Id ":" Type;
syntax Decls = decls: "declare" {IDTYPE ","}* ";";

Decls will be imploded as:

data Decls = decls(list[tuple[str,Type]]);

(assuming Id is a lexical non-terminal).

Example for rule 6

Given the grammar

syntax Formal = formal: "VAR"? {Id ","}+ ":" Type;

The corresponding ADT could be:

data Formal = formal(bool, list[str], Type);
Example for rule 8

Given the grammar

syntax Tag = "[" {Modifier ","}* "]";
syntax Decl = decl: Tag? Signature Body;

In this case, a Decl is imploded into the following ADT:

data Decl = decl(list[Modifier], Signature, Body);
Example for rule 9

Given the grammar

syntax Exp = left add: Exp "+" Exp;

Can be imploded into:

data Exp = add(Exp, Exp);

1.12.22. TreeSearchResult

Types
data TreeSearchResult[&T<:Tree]
     = treeFound(&T tree)
     | treeNotFound()
     ;
Synopsis

Tree search result type for treeAt.

1.12.23. treeAt

Function
  • TreeSearchResult[&T<:Tree] treeAt(type[&T<:Tree] t, loc l, Tree a:appl(_, _))

  • default TreeSearchResult[&T<:Tree] treeAt(type[&T<:Tree] t, loc l, Tree root)

Synopsis

Select the innermost Tree of a given type which is enclosed by a given location.

1.12.24. sameType

Function
  • bool sameType(label(_,Symbol s),Symbol t)

  • bool sameType(Symbol s,label(_,Symbol t))

  • bool sameType(Symbol s,conditional(Symbol t,_))

  • bool sameType(conditional(Symbol s,_), Symbol t)

  • bool sameType(Symbol s, s)

  • default bool sameType(Symbol s, Symbol t)

1.12.25. isNonTerminalType

Function
  • bool isNonTerminalType(Symbol::\sort(str _))

  • bool isNonTerminalType(Symbol::\lex(str _))

  • bool isNonTerminalType(Symbol::\layouts(str _))

  • bool isNonTerminalType(Symbol::\keywords(str _))

  • bool isNonTerminalType(Symbol::\parameterized-sort(str _, list[Symbol] _))

  • bool isNonTerminalType(Symbol::\parameterized-lex(str _, list[Symbol] _))

  • bool isNonTerminalType(Symbol::\start(Symbol s))

  • default bool isNonTerminalType(Symbol s)

Synopsis

Determine if the given type is a non-terminal type.

1.13. Relation

Usage

import Relation;

Synopsis

Library functions for relations.

Description

For operators on relations see Relation in the Rascal Language Reference.

The following functions are defined for relations:

1.13.1. carrier

Function
  • set[&T] carrier (rel[&T,&T] R)

  • set[&T] carrier (rel[&T,&T,&T] R)

  • set[&T] carrier (rel[&T,&T,&T,&T] R)

  • set[&T] carrier (rel[&T,&T,&T,&T,&T] R)

Synopsis

Return the set of all elements in any tuple in a relation.

Examples
rascal>import Relation;
ok
rascal>carrier({<1,10>, <2,20>});
set[int]: {10,1,20,2}
rascal>carrier({<1,10,100,1000>, <2,20,200,2000>});
set[int]: {10,200,20,2,100,1000,1,2000}

1.13.2. carrierR

Function
  • rel[&T,&T] carrierR (rel[&T,&T] R, set[&T] S)

  • rel[&T,&T,&T] carrierR (rel[&T,&T,&T] R, set[&T] S)

  • rel[&T,&T,&T,&T] carrierR (rel[&T,&T,&T,&T] R, set[&T] S)

  • rel[&T,&T,&T,&T,&T] carrierR (rel[&T,&T,&T,&T,&T] R, set[&T] S)

Synopsis

A relation restricted to certain element values in tuples.

Description

Returns relation R restricted to tuples with elements in set S.

Examples
rascal>import Relation;
ok
rascal>carrierR({<1,10>, <2,20>, <3,30>}, {10, 1, 20});
rel[int,int]: {<1,10>}

1.13.3. carrierX

Function
  • rel[&T,&T] carrierX (rel[&T,&T] R, set[&T] S)

  • rel[&T,&T,&T] carrierX (rel[&T,&T,&T] R, set[&T] S)

  • rel[&T,&T,&T,&T] carrierX (rel[&T,&T,&T,&T] R, set[&T] S)

  • rel[&T,&T,&T,&T,&T] carrierX (rel[&T,&T,&T,&T,&T] R, set[&T] S)

Synopsis

A relation excluded tuples containing certain values.

Description

Returns relation R excluding tuples with some element in S.

Examples
rascal>import Relation;
ok
rascal>carrierX({<1,10>, <2,20>, <3,30>}, {10, 1, 20});
rel[int,int]: {<3,30>}

1.13.4. complement

Function
  • rel[&T0, &T1] complement(rel[&T0, &T1] R)

  • rel[&T0, &T1, &T2] complement(rel[&T0, &T1, &T2] R)

  • rel[&T0, &T1, &T2, &T3] complement(rel[&T0, &T1, &T2, &T3] R)

  • rel[&T0, &T1, &T2, &T3, &T4] complement(rel[&T0, &T1, &T2, &T3, &T4] R)

Synopsis

Complement of a relation.

Description

Given a relation R a new relation U can be constructed that contains all possible tuples with element values that occur at corresponding tuple positions in R. The function complement returns the complement of R relative to U, in other words: U - R.

Examples
rascal>import Relation;
ok

Declare R and compute corresponding U:

rascal>R = {<1,10>, <2, 20>, <3, 30>};
rel[int,int]: {
  <1,10>,
  <3,30>,
  <2,20>
}
rascal>U = domain® * range®;
rel[int,int]: {
  <1,10>,
  <1,20>,
  <1,30>,
  <3,10>,
  <3,20>,
  <3,30>,
  <2,10>,
  <2,20>,
  <2,30>
}

Here is the complement of R computed in two ways:

rascal>U - R;
rel[int,int]: {
  <1,20>,
  <1,30>,
  <3,10>,
  <3,20>,
  <2,10>,
  <2,30>
}
rascal>complement({<1,10>, <2, 20>, <3, 30>});
rel[int,int]: {
  <1,20>,
  <1,30>,
  <3,10>,
  <3,20>,
  <2,10>,
  <2,30>
}

1.13.5. domain

Function
  • set[&T0] domain (rel[&T0,&T1] R)

  • set[&T0] domain (rel[&T0,&T1,&T2] R)

  • set[&T0] domain (rel[&T0,&T1,&T2,&T3] R)

  • set[&T0] domain (rel[&T0,&T1,&T2,&T3,&T4] R)

Synopsis

Domain of a relation: a set consisting of the first element of each tuple.

Examples
rascal>import Relation;
ok
rascal>domain({<1,10>, <2,20>});
set[int]: {1,2}
rascal>domain({<"mon", 1>, <"tue", 2>});
set[str]: {"tue","mon"}

1.13.6. domainR

Function
  • rel[&T0,&T1] domainR (rel[&T0,&T1] R, set[&T0] S)

  • rel[&T0,&T1,&T2] domainR (rel[&T0,&T1,&T2] R, set[&T0] S)

  • rel[&T0,&T1,&T2,&T3] domainR (rel[&T0,&T1,&T2,&T3] R, set[&T0] S)

  • rel[&T0,&T1,&T2,&T3,&T4] domainR (rel[&T0,&T1,&T2,&T3,&T4] R, set[&T0] S)

Synopsis

Relation restricted to certain domain elements.

Description

Restriction of a relation R to tuples with first element in S.

Examples
rascal>import Relation;
ok
rascal>domainR({<1,10>, <2,20>, <3,30>}, {3, 1});
rel[int,int]: {
  <1,10>,
  <3,30>
}

1.13.7. domainX

Function
  • rel[&T0,&T1] domainX (rel[&T0,&T1] R, set[&T0] S)

  • rel[&T0,&T1,&T2] domainX (rel[&T0,&T1,&T2] R, set[&T0] S)

  • rel[&T0,&T1,&T2,&T3] domainX (rel[&T0,&T1,&T2,&T3] R, set[&T0] S)

  • rel[&T0,&T1,&T2,&T3,&T4] domainX (rel[&T0,&T1,&T2,&T3,&T4] R, set[&T0] S)

Synopsis

Relation excluding certain domain values.

Description

Relation R excluded tuples with first element in S.

Examples
rascal>import Relation;
ok
rascal>domainX({<1,10>, <2,20>, <3,30>}, {3, 1});
rel[int,int]: {<2,20>}

1.13.8. groupDomainByRange

Function

set[set[&U]] groupDomainByRange(rel[&U dom, &T ran] input)

Synopsis

Make sets of elements in the domain that relate to the same element in the range.

Examples
rascal>import Relation;
ok
rascal>legs = {<"bird", 2>, <"dog", 4>, <"human", 2>, <"spider", 8>, <"millepede", 1000>, <"crab", 8>, <"cat", 4>};
rel[str,int]: {
  <"spider",8>,
  <"human",2>,
  <"crab",8>,
  <"cat",4>,
  <"bird",2>,
  <"dog",4>,
  <"millepede",1000>
}
rascal>groupDomainByRange(legs);
set[set[str]]: {
  {"human","bird"},
  {"cat","dog"},
  {"spider","crab"},
  {"millepede"}
}

1.13.9. groupRangeByDomain

Function

set[set[&T]] groupRangeByDomain(rel[&U dom, &T ran] input)

Synopsis

Make sets of elements in the range that relate to the same element in the domain.

Description
rascal>import Relation;
ok
rascal>skins = {<"bird", "feather">, <"dog", "fur">, <"tortoise", "shell">, <"human", "skin">, <"fish", "scale">, <"lizard", "scale">, <"crab", "shell">, <"cat", "fur">};
rel[str,str]: {
  <"tortoise","shell">,
  <"human","skin">,
  <"crab","shell">,
  <"fish","scale">,
  <"bird","feather">,
  <"dog","fur">,
  <"lizard","scale">,
  <"cat","fur">
}
rascal>groupRangeByDomain(skins);
set[set[str]]: {
  {"scale"},
  {"shell"},
  {"skin"},
  {"feather"},
  {"fur"}
}

1.13.10. ident

Function

rel[&T, &T] ident (set[&T] S)

Synopsis

The identity relation.

Description

The identity relation for set S.

Examples
rascal>import Relation;
ok
rascal>ident({"mon", "tue", "wed"});
rel[str,str]: {
  <"tue","tue">,
  <"mon","mon">,
  <"wed","wed">
}

1.13.11. invert

Function
  • rel[&T1, &T0] invert (rel[&T0, &T1] R)

  • rel[&T2, &T1, &T0] invert (rel[&T0, &T1, &T2] R)

  • rel[&T3, &T2, &T1, &T0] invert (rel[&T0, &T1, &T2, &T3] R)

  • rel[&T4, &T3, &T2, &T1, &T0] invert (rel[&T0, &T1, &T2, &T3, &T4] R)

Synopsis

Invert the tuples in a relation.

Examples
rascal>import Relation;
ok
rascal>invert({<1,10>, <2,20>});
rel[int,int]: {
  <10,1>,
  <20,2>
}

1.13.12. range

Function
  • set[&T1] range (rel[&T0,&T1] R)

  • rel[&T1,&T2] range (rel[&T0,&T1, &T2] R)

  • rel[&T1,&T2,&T3] range (rel[&T0,&T1,&T2,&T3] R)

  • rel[&T1,&T2,&T3,&T4] range (rel[&T0,&T1,&T2,&T3,&T4] R)

Synopsis

The range (i.e., all but the first element of each tuple) of a relation.

Examples
rascal>import Relation;
ok
rascal>range({<1,10>, <2,20>});
set[int]: {10,20}
rascal>range({<"mon", 1>, <"tue", 2>});
set[int]: {1,2}

1.13.13. rangeR

Function

rel[&T0,&T1] rangeR (rel[&T0,&T1] R, set[&T2] S)

Synopsis

Relation restricted to certain range values.

Description

Restriction of binary relation R to tuples with second element in set S.

Examples
rascal>import Relation;
ok
rascal>rangeR({<1,10>, <2,20>, <3,30>}, {30, 10});
rel[int,int]: {
  <1,10>,
  <3,30>
}

1.13.14. rangeX

Function

rel[&T0,&T1] rangeX (rel[&T0,&T1] R, set[&T2] S)

Synopsis

Relation excluding certain range values.

Description

Restriction of binary relation R to tuples with second element not in set S.

Examples
rascal>import Relation;
ok
rascal>rangeX({<1,10>, <2,20>, <3,30>}, {30, 10});
rel[int,int]: {<2,20>}

1.13.15. index

Function

map[&K, set[&V]] index(rel[&K, &V] R)

Synopsis

Indexes a binary relation as a map

Description

Converts a binary relation to a map of the domain to a set of the range.

Examples
rascal>import Relation;
ok
rascal>index({<1,10>, <2,20>, <3,30>, <30,10>});
map[int, set[int]]: (
  1:{10},
  3:{30},
  2:{20},
  30:{10}
)

1.14. Set

Usage

import Set;

Synopsis

Library functions for sets.

Description

For operators on sets see Set in the Rascal Language Reference.

The following functions are defined for sets:

  • classify: Classify elements in a set.

  • group: Group elements in a set given an equivalence function.

  • index: Map set elements to a fixed index.

  • isEmpty: Test whether a set is empty.

  • mapper: Apply a function to all set elements and return set of results.

  • max: Determine the largest element of a set.

  • min: Determine the smallest element of a set.

  • power: Determine the powerset of a set.

  • power1: The powerset (excluding the empty set) of a set value.

  • reducer: Apply a function to successive elements of a set and combine the results (deprecated).

  • size: Determine the number of elements in a set.

  • sum:

  • sum: Sum the elements of a set.

  • getOneFrom: Pick an arbitrary element from a set.

  • getFirstFrom: Get "first" element from a set.

  • takeOneFrom: Remove an arbitrary element from a set, returns the element and a set without that element.

  • takeFirstFrom: Remove "first" element from a set, returns the element and a set without that element.

  • toList: Convert a set to a list.

  • toMap: Convert a set of tuples to a map; each key is associated with a set of values.

  • toMapUnique: Convert a set of tuples to a map (provided that there are no multiple keys).

  • toString: Convert a set to a string.

  • itoString: Convert a set to an indented string.

  • sort: Sort the elements of a set.

  • sort:

  • top: .Synopsis Produce the smallest k elements of a set as sorted by the less function

  • top:

  • union: Flatten a set of sets into a single set

  • jaccard: Compute the Jaccard similarity between two sets

1.14.1. classify

Function

map[&K,set[&V]] classify(set[&V] input, &K (&V) getClass)

Synopsis

Classify elements in a set.

Examples

We classify animals by their number of legs.

rascal>import Set;
ok

Create a map from animals to number of legs.

rascal>legs = ("bird": 2, "dog": 4, "human": 2, "snake": 0, "spider": 8, "millepede": 1000, "crab": 8, "cat": 4);
map[str, int]: ("snake":0,"spider":8,"human":2,"crab":8,"cat":4,"bird":2,"dog":4,"millepede":1000)

Define function nLegs that returns the number of legs for each animal (or 0 when the animal is unknown):

rascal>int nLegs(str animal){
>>>>>>>    return legs[animal] ? 0;
>>>>>>>}
int (str): function(|prompt:///|(0,53,<1,0>,<3,1>))

Now classify a set of animals:

rascal>classify({"bird", "dog", "human", "spider", "millepede", "zebra", "crab", "cat"}, nLegs);
map[int, set[str]]: (
  8:{"spider","crab"},
  2:{"human","bird"},
  4:{"cat","dog"},
  1000:{"millepede"},
  0:{"zebra"}
)

1.14.2. group

Function

set[set[&T]] group(set[&T] input, bool (&T a, &T b) similar)

Synopsis

Group elements in a set given an equivalence function.

Examples

We classify animals by their number of legs.

rascal>import Set;
ok

Create a map from animals to number of legs.

rascal>legs = ("bird": 2, "dog": 4, "human": 2, "snake": 0, "spider": 8, "millepede": 1000, "crab": 8, "cat": 4);
map[str, int]: ("snake":0,"spider":8,"human":2,"crab":8,"cat":4,"bird":2,"dog":4,"millepede":1000)

Define function nLegs that returns the number of legs fro each animal (or 0 when the animal is unknown):

rascal>int nLegs(str animal){
>>>>>>>    return legs[animal] ? 0;
>>>>>>>}
int (str): function(|prompt:///|(0,53,<1,0>,<3,1>))
rascal>bool similar(str a, str b) = nLegs(a) == nLegs(b);
bool (str, str): function(|prompt:///|(0,50,<1,0>,<1,50>))

Now group a set of animals:

rascal>group({"bird", "dog", "human", "spider", "millepede", "zebra", "crab", "cat"}, similar);
set[set[str]]: {
  {"spider"},
  {"zebra"},
  {"human"},
  {"crab"},
  {"cat"},
  {"bird"},
  {"dog"},
  {"millepede"}
}
check compiler.

1.14.3. index

Function

map[&T,int] index(set[&T] s)

Synopsis

Map set elements to a fixed index.

Examples
rascal>import Set;
ok
rascal>index({"elephant", "zebra", "snake"});
map[str, int]: ("snake":2,"zebra":1,"elephant":0)

1.14.4. isEmpty

Function

bool isEmpty(set[&T] st)

Synopsis

Test whether a set is empty.

Description

Yields true if s is empty, and false otherwise.

Examples
rascal>import Set;
ok
rascal>isEmpty({1, 2, 3});
bool: false
rascal>isEmpty({});
bool: true

1.14.5. mapper

Function

set[&U] mapper(set[&T] st, &U (&T) fn)

Synopsis

Apply a function to all set elements and return set of results.

Description

Return a set obtained by applying function fn to all elements of set s.

Examples
rascal>import Set;
ok
rascal>int incr(int x) { return x + 1; }
int (int): function(|prompt:///|(0,33,<1,0>,<1,33>))
rascal>mapper({1, 2, 3, 4}, incr);
set[int]: {5,3,2,4}

1.14.6. max

Function

&T max(set[&T] st)

Synopsis

Determine the largest element of a set.

Examples
rascal>import Set;
ok
rascal>max({1, 3, 5, 2, 4});
int: 5
rascal>max({"elephant", "zebra", "snake"});
str: "zebra"

1.14.7. min

Function

&T min(set[&T] st)

Synopsis

Determine the smallest element of a set.

Examples
rascal>import Set;
ok
rascal>min({1, 3, 5, 4, 2});
int: 1

1.14.8. power

Function

set[set[&T]] power(set[&T] st)

Synopsis

Determine the powerset of a set.

Description

Returns a set with all subsets of s.

Examples
rascal>import Set;
ok
rascal>power({1,2,3,4});
set[set[int]]: {
  {},
  {1,2,4},
  {1},
  {3,2,4},
  {3},
  {1,3,2,4},
  {1,3},
  {2},
  {4},
  {1,2},
  {1,4},
  {3,2},
  {3,4},
  {1,3,2},
  {1,3,4},
  {2,4}
}

1.14.9. power1

Function

set[set[&T]] power1(set[&T] st)

Synopsis

The powerset (excluding the empty set) of a set value.

Description

Returns all subsets (excluding the empty set) of s.

Examples
rascal>import Set;
ok
rascal>power1({1,2,3,4});
set[set[int]]: {
  {1,2,4},
  {1},
  {3,2,4},
  {3},
  {1,3,2,4},
  {1,3},
  {2},
  {4},
  {1,2},
  {1,4},
  {3,2},
  {3,4},
  {1,3,2},
  {1,3,4},
  {2,4}
}

1.14.10. reducer

Function

&T reducer(set[&T] st, &T (&T,&T) fn, &T unit)

Synopsis

Apply a function to successive elements of a set and combine the results (deprecated).

Description

Apply the function fn to successive elements of set s starting with unit.

Examples
rascal>import Set;
ok
rascal>int add(int x, int y) { return x + y; }
int (int, int): function(|prompt:///|(0,39,<1,0>,<1,39>))
rascal>reducer({10, 20, 30, 40}, add, 0);
int: 100
Pitfalls
This function is deprecated, use a reducer instead.

1.14.11. size

Function

int size(set[&T] st)

Synopsis

Determine the number of elements in a set.

Examples
rascal>import Set;
ok
rascal>size({1,2,3,4});
int: 4
rascal>size({"elephant", "zebra", "snake"});
int: 3
rascal>size({});
int: 0

1.14.12. sum

Function
  • (&T <:num) sum(set[(&T <:num)] _:{})

  • default (&T <:num) sum({(&T <: num) e, *(&T <: num) r})

1.14.13. getOneFrom

Function

&T getOneFrom(set[&T] st) throws EmptySet

Synopsis

Pick an arbitrary element from a set.

Examples
rascal>import Set;
ok
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "snake"
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "zebra"
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "zebra"
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "snake"

1.14.14. getFirstFrom

Function

&T getFirstFrom(set[&T] st) throws EmptySet

Synopsis

Get "first" element from a set.

Description

Get "first" element of a set. Of course, sets are unordered and do not have a first element. However, we may assume that sets are internally ordered in some way and this ordering is reproducible. Applying getFirstFrom on the same set will always returns the same element.

Benefits

This function helps to make set-based code more deterministic, for instance, for testing purposes.

1.14.15. takeOneFrom

Function

tuple[&T, set[&T]] takeOneFrom(set[&T] st) throws EmptySet

Synopsis

Remove an arbitrary element from a set, returns the element and a set without that element.

Description

Remove an arbitrary element from set s and return a tuple consisting of the element and a set without that element. Also see getOneFrom.

Examples
rascal>import Set;
ok
rascal>takeOneFrom({1, 2, 3, 4});
tuple[int,set[int]]: <1,{3,2,4}>
rascal>takeOneFrom({1, 2, 3, 4});
tuple[int,set[int]]: <3,{1,2,4}>
rascal>takeOneFrom({1, 2, 3, 4});
tuple[int,set[int]]: <1,{3,2,4}>

1.14.16. takeFirstFrom

Function

tuple[&T, set[&T]] takeFirstFrom(set[&T] st) throws EmptySet

Synopsis

Remove "first" element from a set, returns the element and a set without that element.

Description

element of a set.

1.14.17. toList

Function

list[&T] toList(set[&T] st)

Synopsis

Convert a set to a list.

Examples
rascal>import Set;
ok
rascal>toList({1, 2, 3, 4});
list[int]: [4,2,3,1]
rascal>toList({"elephant", "zebra", "snake"});
list[str]: ["elephant","zebra","snake"]

Note that the same result can be obtained using splicing:

rascal>s = {1,2,3,4};
set[int]: {1,3,2,4}
rascal>l = [*s];
list[int]: [1,3,2,4]
Pitfalls

Recall that the elements of a set are unordered and that there is no guarantee in which order the set elements will be placed in the resulting list.

1.14.18. toMap

Function

map[&A,set[&B]] toMap(rel[&A, &B] st)

Synopsis

Convert a set of tuples to a map; each key is associated with a set of values.

Description

Convert a set of tuples to a map in which the first element of each tuple is associated with the set of second elements of all tuples with the same first element.

Examples
rascal>import Set;
ok
rascal>toMap({<"a", 1>, <"b", 2>, <"a", 10>});
map[str, set[int]]: (
  "a":{10,1},
  "b":{2}
)

1.14.19. toMapUnique

Function

map[&A,&B] toMapUnique(rel[&A, &B] st) throws MultipleKey

Synopsis

Convert a set of tuples to a map (provided that there are no multiple keys).

Description

Convert a set of tuples to a map. The result should be a legal map (i.e., without multiple keys).

Examples
rascal>import Set;
ok
rascal>toMapUnique({<"a", 1>, <"b", 2>, <"c", 10>});
map[str, int]: ("a":1,"b":2,"c":10)

Now explore an erroneous example:

rascal>toMapUnique({<"a", 1>, <"b", 2>, <"a", 10>});
|std:///Set.rsc|(9365,552,<423,0>,<442,70>): MultipleKey("a",10,1)
	at *** somewhere ***(|std:///Set.rsc|(9365,552,<423,0>,<442,70>))
	at toMapUnique(|prompt:///|(39,2,<1,39>,<1,41>))
 
ok

1.14.20. toString

Function

str toString(set[&T] st)

Synopsis

Convert a set to a string.

Examples
rascal>import Set;
ok
rascal>toString({1, 2, 3});
str: "{1,3,2}"
rascal>toString({"elephant", "zebra", "snake"});
str: "{\"snake\",\"zebra\",\"elephant\"}"
Pitfalls

Recall that the elements of a set are unordered and that there is no guarantee in which order the set elements will be placed in the resulting string.

1.14.21. itoString

Function

str itoString(set[&T] st)

Synopsis

Convert a set to an indented string.

Examples
rascal>import Set;
ok
rascal>toString({1, 2, 3});
str: "{1,3,2}"
rascal>toString({"elephant", "zebra", "snake"});
str: "{\"snake\",\"zebra\",\"elephant\"}"
Pitfalls

Recall that the elements of a set are unordered and that there is no guarantee in which order the set elements will be placed in the resulting string.

1.14.22. sort

Function
  • list[&T] sort(set[&T] s)

  • list[&T] sort(set[&T] l, bool (&T a, &T b) less)

Synopsis

Sort the elements of a set.

Sort the elements of a set:

  • Use the built-in ordering on values to compare list elements.

  • Give an additional lessThan function that will be used to compare elements.

This function lessThan (<) function should implement a strict partial order, meaning:

  • that it is not reflexive, i.e. never a < a

  • is anti-symmetric, i.e. never a < b && b < a.

  • is transitive, i.e. if a < b and b < c then a < c.

Examples
rascal>import Set;
ok
rascal>import String;
ok
rascal>sort({10, 4, -2, 11, 100, 5});
list[int]: [-2,4,5,10,11,100]
rascal>fruits = {"mango", "strawberry", "pear", "pineapple", "banana", "grape", "kiwi"};
set[str]: {"mango","banana","pear","pineapple","grape","strawberry","kiwi"}
rascal>sort(fruits);
list[str]: ["banana","grape","kiwi","mango","pear","pineapple","strawberry"]
rascal>sort(fruits, bool(str a, str b){ return size(a) > size(b); });
list[str]: ["strawberry","pineapple","banana","mango","grape","kiwi","pear"]

1.14.23. top

Function
  • list[&T] top(int k, set[&T] l, bool (&T a, &T b) less)

  • list[&T] top(int k, set[&T] l)

Description

This function is fast if k is relatively small, say 10 out of a 1000 elements. It operates in O(n*k) time where n is the size of the set.

If k is a larger value, say k > 10, then it’s perhaps better to just sort the entire set using the asympotically faster (n*log^2(n)) sort function and take the first k elements of the resulting list.

If k is a negative number, top will return the largest abs(k) elements of the set instead of the smallest.

1.14.24. union

Function

set[&T] union(set[set[&T]] sets)

Synopsis

Flatten a set of sets into a single set.

1.14.25. jaccard

Function

real jaccard(set[value] x, set[value] y)

Synopsis

Compute the Jaccard similarity between two sets.

1.15. String

Usage

import String;

Synopsis

Library functions for strings.

Description

For operators on strings see String in the Rascal Language Reference.

The following functions are defined for strings:

  • center: Center a string in given space.

  • center:

  • charAt: Return character in a string by its index position.

  • chars: Return characters of a string.

  • contains: Check that a string contains another string.

  • deescape: Replace escaped characters by the escaped character itself (using Rascal escape conventions)

  • endsWith: Check whether a string ends with a given substring.

  • escape: Replace single characters in a string.

  • findAll: Find all occurrences of a string in another string.

  • findFirst: Find the first occurrence of a string in another string.

  • findLast: Find the last occurrence of a string in another string.

  • isEmpty: Check whether a string is empty.

  • arbString: Generate a arbitrary string.

  • left: Left alignment of string in given space.

  • left:

  • replaceAll: Replace all occurrences of a string in another string.

  • replaceFirst: Replace the first occurrence of a string in another string.

  • replaceLast: Replace the last occurrence of a string in another string.

  • reverse: Return a string with all characters in reverse order.

  • right: Right alignment of a string value in a given space.

  • right:

  • size: Determine length of a string value.

  • startsWith: Check whether a string starts with a given prefix.

  • stringChar: Convert a character code into a string

  • stringChars: Convert a list of character codes into a string

  • isValidCharacter: Check that a given integer value is a valid Unicode code point

  • substring: Extract a substring from a string value.

  • substring:

  • toInt: Convert a string value to integer.

  • toInt:

  • toLowerCase: Convert the characters in a string value to lower case.

  • toReal: Convert a string value to real.

  • toUpperCase: Convert the characters in a string value to upper case.

  • trim: Returns string with leading and trailing whitespace removed.

  • squeeze: Squeeze repeated occurrences of characters.

  • split: Split a string into a list of strings based on a literal separator

  • capitalize:

  • uncapitalize:

  • toBase64:

  • fromBase64:

  • wrap: Word wrap a string to fit in a certain width.

  • format:

  • rexpMatch: Determine if a string matches the given (Java-syntax) regular expression

  • toLocation: Convert a string value to a (source code) location.

  • substitute: Substitute substrings in a string based on a substitution map from location to string.

1.15.1. center

Function
  • str center(str s, int n)

  • str center(str s, int n, str pad)

Synopsis

Center a string in given space.

Description
  • Center string s in string of length n using spaces.

  • Center string s in string of length n using pad as padding character.

Examples
rascal>import String;
ok
rascal>center("abc", 10);
str: "   abc    "
rascal>center("abc", 10, "x");
str: "xxxabcxxxx"

1.15.2. charAt

Function

int charAt(str s, int i) throws IndexOutOfBounds

Synopsis

Return character in a string by its index position.

Description

Return the character at position i in string s as integer character code. Also see stringChar that converts character codes back to string.

Examples
rascal>import String;
ok
rascal>charAt("abc", 0);
int: 97
rascal>stringChar(charAt("abc", 0));
str: "a"

1.15.3. chars

Function

list[int] chars(str s)

Synopsis

Return characters of a string. .Description Return a list of the characters of s as integer character codes. Also see stringChars that converts character codes back to string.

Examples
rascal>import String;
ok
rascal>chars("abc");
list[int]: [97,98,99]
rascal>stringChars(chars("abc")) == "abc";
bool: true

1.15.4. contains

Function

bool contains(str input, str find)

Synopsis

Check that a string contains another string.

Description

Check whether the string find occurs as substring in the string subject.

Examples
rascal>import String;
ok
rascal>contains("abracadabra", "bra");
bool: true
rascal>contains("abracadabra", "e");
bool: false

1.15.5. deescape

Function

str deescape(str s)

Synopsis

Replace escaped characters by the escaped character itself (using Rascal escape conventions).

1.15.6. endsWith

Function

bool endsWith(str subject, str suffix)

Synopsis

Check whether a string ends with a given substring.

Description

Yields true if string subject ends with the string suffix.

Examples
rascal>import String;
ok
rascal>endsWith("Hello.rsc", ".rsc");
bool: true

1.15.7. escape

Function

str escape(str subject, map[str,str] mapping)

Synopsis

Replace single characters in a string.

Description

Return a copy of subject in which each single character key in replacements has been replaced by its associated value.

Examples
rascal>import String;
ok
rascal>import IO;
ok
rascal>escape("abracadabra", ("a" : "AA", "c" : "C"));
str: "AAbrAACAAdAAbrAA"
rascal>L = escape("\"Good Morning\", he said", ("\"": "\\\""));
str: "\\\"Good Morning\\\", he said"
rascal>println(L);
\"Good Morning\", he said
ok

1.15.8. findAll

Function

list[int] findAll(str subject, str find)

Synopsis

Find all occurrences of a string in another string.

Description

Find all occurrences of string find in string subject. The result is a (possible empty) list of positions where find matches.

See also findFirst and findLast.

Examples
rascal>import String;
ok
rascal>findAll("abracadabra", "a");
list[int]: [0,3,5,7,10]
rascal>findAll("abracadabra", "bra");
list[int]: [1,8]
rascal>findAll("abracadabra", "e");
list[int]: []

1.15.9. findFirst

Function

int findFirst(str subject, str find)

Synopsis

Find the first occurrence of a string in another string.

Description

Find the first occurrence of string find in string subject. The result is either a position in subject or -1 when find is not found.

Also see findAll and findLast.

Examples
rascal>import String;
ok
rascal>findFirst("abracadabra", "a");
int: 0
rascal>findFirst("abracadabra", "bra");
int: 1
rascal>findFirst("abracadabra", "e");
int: -1

1.15.10. findLast

Function

int findLast(str subject, str find)

Synopsis

Find the last occurrence of a string in another string.

Description

Find the last occurrence of string find in string subject. The result is either a position in subject or -1 when find is not found.

Also see findAll and findFirst.

Examples
rascal>import String;
ok
rascal>findLast("abracadabra", "a");
int: 10
rascal>findLast("abracadabra", "bra");
int: 8
rascal>findLast("abracadabra", "e");
int: -1

1.15.11. isEmpty

Function

bool isEmpty(str s)

Synopsis

Check whether a string is empty.

Description

Returns true if string s is empty.

Examples
rascal>import String;
ok
rascal>isEmpty("");
bool: true
rascal>isEmpty("abc");
bool: false

1.15.12. arbString

Function

str arbString(int n)

Synopsis

Generate a arbitrary string.

Description

Returns a string of maximum n length, with arbitrary characters.

Examples
rascal>import String;
ok
rascal>arbString(3);
str: "7jf"
rascal>arbString(10);
str: ""

1.15.13. left

Function
  • str left(str s, int n)

  • str left(str s, int n, str pad)

Synopsis

Left alignment of string in given space.

Description
  • Left align string s in string of length n using spaces.

  • Left align string s in string of length n using pad as pad character.

Examples
rascal>import String;
ok
rascal>left("abc", 10);
str: "abc       "
rascal>left("abc", 10, "x");
str: "abcxxxxxxx"

1.15.14. replaceAll

Function

str replaceAll(str subject, str find, str replacement)

Synopsis

Replace all occurrences of a string in another string.

Description

Return a copy of subject in which all occurrences of find (if any) have been replaced by replacement. Also see replaceFirst and replaceLast.

Examples
rascal>import String;
ok
rascal>replaceAll("abracadabra", "a", "A");
str: "AbrAcAdAbrA"
rascal>replaceAll("abracadabra", "ra", "RARA");
str: "abRARAcadabRARA"
rascal>replaceAll("abracadabra", "cra", "CRA");
str: "abracadabra"
Pitfalls

Note that find is a string (as opposed to, for instance, a regular expression in Java).

1.15.15. replaceFirst

Function

str replaceFirst(str subject, str find, str replacement)

Synopsis

Replace the first occurrence of a string in another string.

Description

Return a copy of subject in which the first occurrence of find (if it exists) has been replaced by replacement. Also see replaceAll and replaceLast.

Examples
rascal>import String;
ok
rascal>replaceFirst("abracadabra", "a", "A");
str: "Abracadabra"
rascal>replaceFirst("abracadabra", "ra", "RARA");
str: "abRARAcadabra"
rascal>replaceFirst("abracadabra", "cra", "CRA");
str: "abracadabra"
Pitfalls

Note that find is a string (as opposed to, for instance, a regular expression in Java).

1.15.16. replaceLast

Function

str replaceLast(str subject, str find, str replacement)

Synopsis

Replace the last occurrence of a string in another string.

Description

Return a copy of subject in which the last occurrence of find (if it exists) has been replaced by replacement. Also see replaceFirst and replaceLast.

Examples
rascal>import String;
ok
rascal>replaceLast("abracadabra", "a", "A");
str: "abracadabrA"
rascal>replaceLast("abracadabra", "ra", "RARA");
str: "abracadabRARA"
rascal>replaceLast("abracadabra", "cra", "CRA");
str: "abracadabra"
Pitfalls

Note that find is a string (as opposed to, for instance, a regular expression in Java).

1.15.17. reverse

Function

str reverse(str s)

Synopsis

Return a string with all characters in reverse order.

Description

Returns string with all characters of string s in reverse order.

Examples
rascal>import String;
ok
rascal>reverse("abc");
str: "cba"

1.15.18. right

Function
  • str right(str s, int n)

  • str right(str s, int n, str pad)

Synopsis

Right alignment of a string value in a given space.

Description
  • Right align string s in string of length n using spaces.

  • Right align string s in string of length n using pad as pad character.

Examples
rascal>import String;
ok
rascal>right("abc", 10);
str: "       abc"
rascal>right("abc", 10, "x");
str: "xxxxxxxabc"

1.15.19. size

Function

int size(str s)

Synopsis

Determine length of a string value.

Description

Returns the length (number of characters) in string s.

Examples
rascal>import String;
ok
rascal>size("abc");
int: 3
rascal>size("");
int: 0

1.15.20. startsWith

Function

bool startsWith(str subject, str prefix)

Synopsis

Check whether a string starts with a given prefix.

Description

Yields true if string subject starts with the string prefix.

Examples
rascal>import String;
ok
rascal>startsWith("Hello.rsc", "Hell");
bool: true

1.15.21. stringChar

Function

str stringChar(int char) throws IllegalArgument

Synopsis

Convert a character code into a string.

1.15.22. stringChars

Function

str stringChars(list[int] chars) throws IllegalArgument

Synopsis

Convert a list of character codes into a string.

1.15.23. isValidCharacter

Function

bool isValidCharacter(int ch)

Synopsis

Check that a given integer value is a valid Unicode code point.

1.15.24. substring

Function
  • str substring(str s, int begin)

  • str substring(str s, int begin, int end)

Synopsis

Extract a substring from a string value.

Description
  • Yields substring of string s from index begin to the end of the string.

  • Yields substring of string s from index begin to (but not including) index end.

Examples
rascal>import String;
ok
rascal>substring("abcdef", 2);
str: "cdef"
rascal>substring("abcdef", 2, 4);
str: "cd"

1.15.25. toInt

Function
  • int toInt(str s) throws IllegalArgument

  • int toInt(str s, int r) throws IllegalArgument

Synopsis

Convert a string value to integer.

Description
  • Converts string s to integer.

  • Convert string s to integer using radix r.

Throws IllegalArgument when s cannot be converted.

Examples
rascal>import String;
ok
rascal>toInt("11");
int: 11
rascal>toInt("11", 8);
int: 9

Now try an erroneous argument:

rascal>toInt("abc");
|std:///String.rsc|(11013,490,<504,0>,<530,52>): IllegalArgument("abc","For input string: \"abc\"")
	at *** somewhere ***(|std:///String.rsc|(11013,490,<504,0>,<530,52>))
	at toInt(|prompt:///|(6,5,<1,6>,<1,11>))
 
ok

1.15.26. toLowerCase

Function

str toLowerCase(str s)

Synopsis

Convert the characters in a string value to lower case.

Description

Convert all characters in string s to lowercase. Also see toUpperCase.

Examples
rascal>import String;
ok
rascal>toLowerCase("AaBbCc123");
str: "aabbcc123"

1.15.27. toReal

Function

real toReal(str s)

Synopsis

Convert a string value to real.

Description

Converts string s to a real. Throws IllegalArgument when s cannot be converted.

Examples
rascal>import String;
ok
rascal>toReal("2.5e-3");
real: 0.0025
rascal>toReal("123");
real: 123.
rascal>toReal("abc");
|std:///String.rsc|(11937,335,<553,0>,<570,31>): IllegalArgument()
	at *** somewhere ***(|std:///String.rsc|(11937,335,<553,0>,<570,31>))
	at toReal(|prompt:///|(7,5,<1,7>,<1,12>))
 
ok

1.15.28. toUpperCase

Function

str toUpperCase(str s)

Synopsis

Convert the characters in a string value to upper case.

Description

Converts all characters in string s to upper case.

Also see toLowerCase.

Examples
rascal>import String;
ok
rascal>toUpperCase("AaBbCc123");
str: "AABBCC123"

1.15.29. trim

Function

str trim(str s)

Synopsis

Returns string with leading and trailing whitespace removed.

Examples
rascal>import String;
ok
rascal>trim("  jelly
>>>>>>>beans  ");
str: "jelly\nbeans"

1.15.30. squeeze

Function

str squeeze(str src, str charSet)

Synopsis

Squeeze repeated occurrences of characters. .Description Squeeze repeated occurrences in src of characters in charSet removed. See Apache for the allowed syntax in charSet.

Examples
rascal>import String;
ok
rascal>squeeze("hello", "el");
str: "helo"

1.15.31. split

Function

list[str] split(str sep, str src)

Synopsis

Split a string into a list of strings based on a literal separator.

1.15.32. capitalize

Function

str capitalize(str src)

1.15.33. uncapitalize

Function

str uncapitalize(str src)

1.15.34. toBase64

Function

str toBase64(str src)

1.15.35. fromBase64

Function

str fromBase64(str src)

1.15.36. wrap

Function

str wrap(str src, int wrapLength)

Synopsis

Word wrap a string to fit in a certain width.

Description

Inserts newlines in a string in order to fit the string in a certain width. It only breaks on spaces (' ').

1.15.37. format

Function

str format(str s, str dir, int n, str pad)

1.15.38. rexpMatch

Function

bool rexpMatch(str s, str re)

Synopsis

Determine if a string matches the given (Java-syntax) regular expression.

1.15.39. toLocation

Function

loc toLocation(str s)

Synopsis

Convert a string value to a (source code) location.

Description
  • Converts string s to a location.

  • If the scheme is not provided, it is assumed to be cwd.

Examples
rascal>import String;
ok
rascal>toLocation("http://grammarware.net");
loc: |http://grammarware.net|
rascal>toLocation("document.xml");
loc: |cwd:///document.xml|

1.15.40. substitute

Function

str substitute(str src, map[loc,str] s)

Synopsis

Substitute substrings in a string based on a substitution map from location to string.

Examples
rascal>import String;
ok
rascal>substitute("abc", (|stdin:///|(1,1): "d"))
str: "adc"

1.16. Type

Usage

import Type;

Synopsis

Rascal’s type system, implemented in Rascal itself.

Description

The goal of this module is to provide:

  • reflection capabilities that are useful for deserialization and validation of data, and

  • to provide the basic building blocks for syntax trees (see ParseTree)

The following definition is built into Rascal:

data type[&T] = type(Symbol symbol, map[Symbol,Production] definitions);

The # operator will always produce a value of type[&T], where &T is bound to the type that was reified.

Examples
rascal>import Type;
ok
rascal>#int
type[int]: type(
  int(),
  ())
rascal>#rel[int,int]
type[rel[int,int]]: type(
  set(tuple([
        int(),
        int()
      ])),
  ())
rascal>data B = t();
ok
rascal>#B
type[B]: type(
  adt(
    "B",
    []),
  (adt(
      "B",
      []):choice(
      adt(
        "B",
        []),
      {cons(
          label(
            "t",
            adt(
              "B",
              [])),
          [],
          [],
          {})})))
rascal>syntax A = "a";
ok
rascal>#A;
type[A]: type(
  sort("A"),
  (
    layouts("$default$"):choice(
      layouts("$default$"),
      {prod(
          layouts("$default$"),
          [],
          {})}),
    empty():choice(
      empty(),
      {prod(
          empty(),
          [],
          {})}),
    sort("A"):choice(
      sort("A"),
      {prod(
          sort("A"),
          [lit("a")],
          {})})
  ))
rascal>type(\int(),())
type[value]: type(
  int(),
  ())

The following functions are provided on types:

1.16.1. Symbol

Types
data Symbol
     = \int()
     | \bool()
     | \real()
     | \rat()
     | \str()
     | \num()
     | \node()
     | \void()
     | \value()
     | \loc()
     | \datetime()
     ;
Synopsis

A Symbol represents a Rascal Type.

Description

Symbols are values that represent Rascal’s types. These are the atomic types. We define here:

1 Atomic types.
2 Labels that are used to give names to symbols, such as field names, constructor names, etc.
3 Composite types.
4 Parameters that represent a type variable.

In ParseTree, see Symbol, Symbols will be further extended with the symbols that may occur in a ParseTree.

1.16.2. Symbol

Types
data Symbol
     = \label(str name, Symbol symbol)
     ;

1.16.3. Symbol

Types
data Symbol
     = \set(Symbol symbol)
     | \rel(list[Symbol] symbols)
     | \lrel(list[Symbol] symbols)
     | \tuple(list[Symbol] symbols)
     | \list(Symbol symbol)
     | \map(Symbol from, Symbol to)
     | \bag(Symbol symbol)
     | \adt(str name, list[Symbol] parameters)
     | \cons(Symbol \adt, str name, list[Symbol] parameters)
     | \alias(str name, list[Symbol] parameters, Symbol aliased)
     | \func(Symbol ret, list[Symbol] parameters, list[Symbol] kwTypes)
     | \func(Symbol ret, list[Symbol] parameters)
     | \overloaded(set[Symbol] alternatives)
     | \var-func(Symbol ret, list[Symbol] parameters, Symbol varArg)
     | \reified(Symbol symbol)
     ;

1.16.4. Symbol

Types
data Symbol
     = \parameter(str name, Symbol bound)
     ;

1.16.5. Production

Types
data Production
     = \cons(Symbol def, list[Symbol] symbols, list[Symbol] kwTypes, set[Attr] attributes)
     | \func(Symbol def, list[Symbol] symbols, list[Symbol] kwTypes, set[Attr] attributes /*, str code = "", map[str,value] bindings = (), loc cpe = |unknown:///|*/)
     | \choice(Symbol def, set[Production] alternatives)
     | \composition(Production lhs, Production rhs)
     ;
Synopsis

A production in a grammar or constructor in a data type.

Description

Productions represent abstract (recursive) definitions of abstract data type constructors and functions:

  • cons: a constructor for an abstract data type.

  • func: a function.

  • choice: the choice between various alternatives.

  • composition: composition of two productions.

In ParseTree, see Production, Productions will be further extended and will be used to represent productions in syntax rules.

1.16.6. Attr

Types
data Attr
     = \tag(value \tag)
     ;
Synopsis

Attributes register additional semantics annotations of a definition.

[[Type-\var-func]] ## \var-func

Function

Symbol \var-func(Symbol ret, list[Symbol] parameters, Symbol varArg)

Synopsis

Transform a function with varargs (…​) to a normal function with a list argument.

1.16.7. choice

Function

Production choice(Symbol s, set[Production] choices)

Synopsis

Normalize the choice between alternative productions.

Description

Nested choice is flattened.

1.16.8. subtype

Function
  • bool subtype(type[&T] t, type[&U] u)

  • bool subtype(Symbol s, s)

  • default bool subtype(Symbol s, Symbol t)

  • bool subtype(Symbol _, Symbol::\value())

  • bool subtype(Symbol::\void(), Symbol _)

  • bool subtype(Symbol::\cons(Symbol a, _, list[Symbol] _), a)

  • bool subtype(Symbol::\cons(Symbol a, str name, list[Symbol] ap), Symbol::\cons(a,name,list[Symbol] bp))

  • bool subtype(Symbol::\adt(str _, list[Symbol] _), Symbol::\node())

  • bool subtype(Symbol::\adt(str n, list[Symbol] l), Symbol::\adt(n, list[Symbol] r))

  • bool subtype(Symbol::\alias(str _, list[Symbol] _, Symbol aliased), Symbol r)

  • bool subtype(Symbol l, \alias(str _, list[Symbol] _, Symbol aliased))

  • bool subtype(Symbol::\int(), Symbol::\num())

  • bool subtype(Symbol::\rat(), Symbol::\num())

  • bool subtype(Symbol::\real(), Symbol::\num())

  • bool subtype(Symbol::\tuple(list[Symbol] l), \tuple(list[Symbol] r))

  • bool subtype(Symbol::\list(Symbol s), Symbol::\list(Symbol t))

  • bool subtype(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • bool subtype(Symbol::\list(Symbol s), Symbol::\lrel(list[Symbol] r))

  • bool subtype(Symbol::\lrel(list[Symbol] l), \list(Symbol r))

  • bool subtype(Symbol::\set(Symbol s), Symbol::\set(Symbol t))

  • bool subtype(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • bool subtype(Symbol::\set(Symbol s), Symbol::\rel(list[Symbol] r))

  • bool subtype(Symbol::\rel(list[Symbol] l), Symbol::\set(Symbol r))

  • bool subtype(Symbol::\bag(Symbol s), Symbol::\bag(Symbol t))

  • bool subtype(Symbol::\map(Symbol from1, Symbol to1), Symbol::\map(Symbol from2, Symbol to2))

  • bool subtype(Symbol::\func(Symbol r1, list[Symbol] p1, list[Symbol] _), Symbol f2)

  • bool subtype(Symbol f2, Symbol::\func(Symbol r1, list[Symbol] p1, list[Symbol] _))

  • bool subtype(Symbol::\func(Symbol r1, list[Symbol] p1), Symbol::\func(Symbol r2, list[Symbol] p2))

  • bool subtype(Symbol::\parameter(str _, Symbol bound), Symbol r)

  • bool subtype(Symbol l, Symbol::\parameter(str _, Symbol bound))

  • bool subtype(Symbol::\label(str _, Symbol s), Symbol t)

  • bool subtype(Symbol s, Symbol::\label(str _, Symbol t))

  • bool subtype(Symbol::\reified(Symbol s), Symbol::\reified(Symbol t))

  • bool subtype(Symbol::\reified(Symbol s), Symbol::\node())

  • bool subtype(list[Symbol] l, list[Symbol] r)

  • default bool subtype(list[Symbol] l, list[Symbol] r)

Synopsis

Subtype on types.

1.16.9. comparable

Function

bool comparable(Symbol s, Symbol t)

Synopsis

Check if two types are comparable, i.e., have a common supertype.

1.16.10. equivalent

Function

bool equivalent(Symbol s, Symbol t)

Synopsis

Check if two types are equivalent.

1.16.11. eq

Function

bool eq(value x, value y)

Synopsis

Structural equality between values.

Description

The difference is that no implicit coercions are done between values of incomparable types, such as == does for int, real and rat.

Examples
rascal>import Type;
ok
rascal>1 == 1.0
bool: true
rascal>eq(1,1.0)
bool: false

1.16.12. lub

Function
  • Symbol lub(Symbol s, s)

  • default Symbol lub(Symbol s, Symbol t)

  • Symbol lub(Symbol::\value(), Symbol t)

  • Symbol lub(Symbol s, Symbol::\value())

  • Symbol lub(Symbol::\void(), Symbol t)

  • Symbol lub(Symbol s, Symbol::\void())

  • Symbol lub(Symbol::\int(), Symbol::\num())

  • Symbol lub(Symbol::\int(), Symbol::\real())

  • Symbol lub(Symbol::\int(), Symbol::\rat())

  • Symbol lub(Symbol::\rat(), Symbol::\num())

  • Symbol lub(Symbol::\rat(), Symbol::\real())

  • Symbol lub(Symbol::\rat(), Symbol::\int())

  • Symbol lub(Symbol::\real(), Symbol::\num())

  • Symbol lub(Symbol::\real(), Symbol::\int())

  • Symbol lub(Symbol::\real(), Symbol::\rat())

  • Symbol lub(Symbol::\num(), Symbol::\int())

  • Symbol lub(Symbol::\num(), Symbol::\real())

  • Symbol lub(Symbol::\num(), Symbol::\rat())

  • Symbol lub(Symbol::\set(Symbol s), Symbol::\set(Symbol t))

  • Symbol lub(Symbol::\set(Symbol s), Symbol::\rel(list[Symbol] ts))

  • Symbol lub(Symbol::\rel(list[Symbol] ts), Symbol::\set(Symbol s))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol lub(Symbol::\list(Symbol s), Symbol::\list(Symbol t))

  • Symbol lub(Symbol::\list(Symbol s), \lrel(list[Symbol] ts))

  • Symbol lub(Symbol::\lrel(list[Symbol] ts), Symbol::\list(Symbol s))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol lub(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol lub(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol lub(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol lub(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol lub(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol lub(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol lub(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol lub(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(Symbol rf, Symbol rt))

  • Symbol lub(Symbol::\map(Symbol lf, Symbol lt), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol lub(Symbol::\map(Symbol lf, Symbol lt), Symbol::\map(Symbol rf, Symbol rt))

  • Symbol lub(Symbol::\bag(Symbol s), Symbol::\bag(Symbol t))

  • Symbol lub(Symbol::\adt(str n, list[Symbol] _), Symbol::\node())

  • Symbol lub(Symbol::\node(), \adt(str n, list[Symbol] _))

  • Symbol lub(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(n, list[Symbol] rp))

  • Symbol lub(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(n, list[Symbol] rp))

  • Symbol lub(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(str m, list[Symbol] rp))

  • Symbol lub(Symbol::\adt(str ln, list[Symbol] lp), Symbol::\cons(Symbol b, _, list[Symbol] _))

  • Symbol lub(Symbol::\cons(Symbol la, _, list[Symbol] _), Symbol::\cons(Symbol ra, _, list[Symbol] _))

  • Symbol lub(Symbol::\cons(Symbol a, _, list[Symbol] lp), Symbol::\adt(str n, list[Symbol] rp))

  • Symbol lub(Symbol::\cons(Symbol _, _, list[Symbol] _), Symbol::\node())

  • Symbol lub(Symbol::\alias(str _, list[Symbol] _, Symbol aliased), Symbol r)

  • Symbol lub(Symbol l, \alias(str _, list[Symbol] _, Symbol aliased))

Synopsis

The least-upperbound (lub) between two types.

Description

This function documents and implements the lub operation in Rascal’s type system.

1.16.13. keepParams

Function

bool keepParams(Symbol::\parameter(str s1, Symbol bound1), Symbol::\parameter(str s2, Symbol bound2))

1.16.14. lub

Function
  • Symbol lub(Symbol l:Symbol::\parameter(str s1, Symbol bound1), Symbol r:Symbol::\parameter(str s2, Symbol bound2))

  • Symbol lub(Symbol l:Symbol::\parameter(str s1, Symbol bound1), Symbol r:Symbol::\parameter(str s2, Symbol bound2))

  • Symbol lub(Symbol::\parameter(str _, Symbol bound), Symbol r)

  • Symbol lub(Symbol l, Symbol::\parameter(str _, Symbol bound))

  • Symbol lub(Symbol::\reified(Symbol l), Symbol::\reified(Symbol r))

  • Symbol lub(Symbol::\reified(Symbol l), Symbol::\node())

  • Symbol lub(Symbol::\func(Symbol lr, list[Symbol] lp, list[Symbol] lkw), Symbol::\func(Symbol rr, list[Symbol] rp, list[Symbol] rkw))

  • Symbol lub(Symbol::\label(_,Symbol l), Symbol r)

  • Symbol lub(Symbol l, Symbol::\label(_,Symbol r))

  • list[Symbol] lub(list[Symbol] l, list[Symbol] r)

  • default list[Symbol] lub(list[Symbol] l, list[Symbol] r)

1.16.15. allLabeled

Function

bool allLabeled(list[Symbol] l)

1.16.16. noneLabeled

Function

bool noneLabeled(list[Symbol] l)

1.16.17. getLabels

Function

list[str] getLabels(list[Symbol] l)

1.16.18. addLabels

Function
  • list[Symbol] addLabels(list[Symbol] l, list[str] s)

  • default list[Symbol] addLabels(list[Symbol] l, list[str] s)

1.16.19. stripLabels

Function

list[Symbol] stripLabels(list[Symbol] l)

1.16.20. getParamLabels

Function

list[str] getParamLabels(list[Symbol] l)

1.16.21. addParamLabels

Function
  • list[Symbol] addParamLabels(list[Symbol] l, list[str] s)

  • default list[Symbol] addParamLabels(list[Symbol] l, list[str] s)

1.16.22. glb

Function
  • Symbol glb(Symbol s, s)

  • default Symbol glb(Symbol s, Symbol t)

  • Symbol glb(Symbol::\void(), Symbol t)

  • Symbol glb(Symbol s, Symbol::\void())

  • Symbol glb(Symbol::\value(), Symbol t)

  • Symbol glb(Symbol s, Symbol::\value())

  • Symbol glb(Symbol::\int(), Symbol::\num())

  • Symbol glb(Symbol::\num(), Symbol::\int())

  • Symbol glb(Symbol::\rat(),Symbol::\num())

  • Symbol glb(Symbol::\num(), Symbol::\rat())

  • Symbol glb(Symbol::\real(), Symbol::\num())

  • Symbol glb(Symbol::\num(), Symbol::\real())

  • Symbol glb(Symbol::\set(Symbol s), Symbol::\set(Symbol t))

  • Symbol glb(Symbol::\set(Symbol s), Symbol::\rel(list[Symbol] ts))

  • Symbol glb(Symbol::\rel(list[Symbol] ts), Symbol::\set(Symbol s))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\rel(list[Symbol] l), Symbol::\rel(list[Symbol] r))

  • Symbol glb(Symbol::\list(Symbol s), Symbol::\list(Symbol t))

  • Symbol glb(Symbol::\list(Symbol s), Symbol::\lrel(list[Symbol] ts))

  • Symbol glb(Symbol::\lrel(list[Symbol] ts), Symbol::\list(Symbol s))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\lrel(list[Symbol] l), Symbol::\lrel(list[Symbol] r))

  • Symbol glb(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol glb(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol glb(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol glb(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol glb(Symbol::\tuple(list[Symbol] l), Symbol::\tuple(list[Symbol] r))

  • Symbol glb(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol glb(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol glb(Symbol::\map(\label(str lfl, Symbol lf), \label(str ltl, Symbol lt)), Symbol::\map(Symbol rf, Symbol rt))

  • Symbol glb(Symbol::\map(Symbol lf, Symbol lt), Symbol::\map(\label(str rfl, Symbol rf), \label(str rtl, Symbol rt)))

  • Symbol glb(Symbol::\map(Symbol lf, Symbol lt), Symbol::\map(Symbol rf, Symbol rt))

  • Symbol glb(Symbol::\bag(Symbol s), Symbol::\bag(Symbol t))

  • Symbol glb(Symbol::\adt(str n, list[Symbol] _), Symbol::\node())

  • Symbol glb(\node(), Symbol::\adt(str n, list[Symbol] _))

  • Symbol glb(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(n, list[Symbol] rp))

  • Symbol glb(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(n, list[Symbol] rp))

  • Symbol glb(Symbol::\adt(str n, list[Symbol] lp), Symbol::\adt(str m, list[Symbol] rp))

  • Symbol glb(Symbol::\adt(str ln, list[Symbol] lp), Symbol::\cons(Symbol b, _, list[Symbol] _))

  • Symbol glb(Symbol::\cons(Symbol la, _, list[Symbol] _), Symbol::\cons(Symbol ra, _, list[Symbol] _))

  • Symbol glb(Symbol::\cons(Symbol a, _, list[Symbol] lp), Symbol::\adt(str n, list[Symbol] rp))

  • Symbol glb(Symbol::\cons(Symbol _, _, list[Symbol] _), \node())

  • Symbol glb(Symbol::\alias(str _, list[Symbol] _, Symbol aliased), Symbol r)

  • Symbol glb(Symbol l, Symbol::\alias(str _, list[Symbol] _, Symbol aliased))

  • Symbol glb(Symbol::\parameter(str _, Symbol bound), Symbol r)

  • Symbol glb(Symbol l, Symbol::\parameter(str _, Symbol bound))

  • Symbol glb(Symbol::\reified(Symbol l), Symbol::\reified(Symbol r))

  • Symbol glb(Symbol::\reified(Symbol l), Symbol::\node())

  • Symbol glb(Symbol::\func(Symbol lr, list[Symbol] lp, list[Symbol] lkw), Symbol::\func(Symbol rr, list[Symbol] rp, list[Symbol] rkw))

  • Symbol glb(Symbol::\label(_,Symbol l), Symbol r)

  • Symbol glb(Symbol l, Symbol::\label(_,Symbol r))

  • list[Symbol] glb(list[Symbol] l, list[Symbol] r)

  • default list[Symbol] glb(list[Symbol] l, list[Symbol] r)

Synopsis

The greatest lower bound (glb) between two types.

Description

This function documents and implements the glb operation in Rascal’s type system.

1.16.23. Exception

Types
data Exception
     = typeCastException(Symbol from, type[value] to)
     ;

1.16.24. typeCast

Function

&T typeCast(type[&T] typ, value v)

1.16.25. make

Function
  • &T make(type[&T] typ, str name, list[value] args)

  • &T make(type[&T] typ, str name, list[value] args, map[str,value] keywordArgs)

Synopsis

Instantiate an ADT constructor of a given type with the given children and optional keyword arguments.

Description

This function will build a constructor if the definition exists and throw an exception otherwise.

1.16.26. typeOf

Function

Symbol typeOf(value v)

Synopsis

Returns the dynamic type of a value as a reified type.

Description

As opposed to the # operator, which produces the type of a value statically, this function produces the dynamic type of a value, represented by a symbol.

Examples
rascal>import Type;
ok
rascal>value x = 1;
value: 1
rascal>typeOf(x)
Symbol: int()
Pitfalls
  • Note that the typeOf function does not produce definitions, like the reify operator # does, since values may escape the scope in which they’ve been constructed leaving their contents possibly undefined.

1.16.27. isIntType

Function
  • bool isIntType(Symbol::\alias(,,Symbol at))

  • bool isIntType(Symbol::\parameter(_,Symbol tvb))

  • bool isIntType(Symbol::\label(_,Symbol lt))

  • bool isIntType(Symbol::\int())

  • default bool isIntType(Symbol _)

Synopsis

Determine if the given type is an int.

1.16.28. isBoolType

Function
  • bool isBoolType(Symbol::\alias(,,Symbol at))

  • bool isBoolType(Symbol::\parameter(_,Symbol tvb))

  • bool isBoolType(Symbol::\label(_,Symbol lt))

  • bool isBoolType(Symbol::\bool())

  • default bool isBoolType(Symbol _)

Synopsis

Determine if the given type is a bool.

1.16.29. isRealType

Function
  • bool isRealType(Symbol::\alias(,,Symbol at))

  • bool isRealType(Symbol::\parameter(_,Symbol tvb))

  • bool isRealType(Symbol::\label(_,Symbol lt))

  • bool isRealType(Symbol::\real())

  • default bool isRealType(Symbol _)

Synopsis

Determine if the given type is a real.

1.16.30. isRatType

Function
  • bool isRatType(Symbol::\alias(,,Symbol at))

  • bool isRatType(Symbol::\parameter(_,Symbol tvb))

  • bool isRatType(Symbol::\label(_,Symbol lt))

  • bool isRatType(Symbol::\rat())

  • default bool isRatType(Symbol _)

Synopsis

Determine if the given type is a rational.

1.16.31. isStrType

Function
  • bool isStrType(Symbol::\alias(,,Symbol at))

  • bool isStrType(Symbol::\parameter(_,Symbol tvb))

  • bool isStrType(Symbol::\label(_,Symbol lt))

  • bool isStrType(Symbol::\str())

  • default bool isStrType(Symbol _)

Synopsis

Determine if the given type is a string.

1.16.32. isNumType

Function
  • bool isNumType(Symbol::\alias(,,Symbol at))

  • bool isNumType(Symbol::\parameter(_,Symbol tvb))

  • bool isNumType(Symbol::\label(_,Symbol lt))

  • bool isNumType(Symbol::\num())

  • default bool isNumType(Symbol _)

Synopsis

Determine if the given type is a num.

1.16.33. isNodeType

Function
  • bool isNodeType(Symbol::\alias(,,Symbol at))

  • bool isNodeType(Symbol::\parameter(_,Symbol tvb))

  • bool isNodeType(Symbol::\label(_,Symbol lt))

  • bool isNodeType(Symbol::\node())

  • bool isNodeType(Symbol::\adt(,))

  • default bool isNodeType(Symbol _)

Synopsis

Determine if the given type is a node.

1.16.34. isVoidType

Function
  • bool isVoidType(Symbol::\alias(,,Symbol at))

  • bool isVoidType(Symbol::\parameter(_,Symbol tvb))

  • bool isVoidType(Symbol::\label(_,Symbol lt))

  • bool isVoidType(Symbol::\void())

  • default bool isVoidType(Symbol _)

Synopsis

Determine if the given type is a void.

1.16.35. isValueType

Function
  • bool isValueType(Symbol::\alias(,,Symbol at))

  • bool isValueType(Symbol::\parameter(_,Symbol tvb))

  • bool isValueType(Symbol::\label(_,Symbol lt))

  • bool isValueType(Symbol::\value())

  • default bool isValueType(Symbol _)

Synopsis

Determine if the given type is a value.

1.16.36. isLocType

Function
  • bool isLocType(Symbol::\alias(,,Symbol at))

  • bool isLocType(Symbol::\parameter(_,Symbol tvb))

  • bool isLocType(Symbol::\label(_,Symbol lt))

  • bool isLocType(Symbol::\loc())

  • default bool isLocType(Symbol _)

Synopsis

Determine if the given type is a loc.

1.16.37. isDateTimeType

Function
  • bool isDateTimeType(Symbol::\alias(,,Symbol at))

  • bool isDateTimeType(Symbol::\parameter(_,Symbol tvb))

  • bool isDateTimeType(Symbol::\label(_,Symbol lt))

  • bool isDateTimeType(Symbol::\datetime())

  • default bool isDateTimeType(Symbol _)

Synopsis

Determine if the given type is a datetime.

1.16.38. isSetType

Function
  • bool isSetType(Symbol::\alias(,,Symbol at))

  • bool isSetType(Symbol::\parameter(_,Symbol tvb))

  • bool isSetType(Symbol::\label(_,Symbol lt))

  • bool isSetType(Symbol::\set(_))

  • bool isSetType(Symbol::\rel(_))

  • default bool isSetType(Symbol _)

Synopsis

Determine if the given type is a set.

1.16.39. isRelType

Function
  • bool isRelType(Symbol::\alias(,,Symbol at))

  • bool isRelType(Symbol::\parameter(_,Symbol tvb))

  • bool isRelType(Symbol::\label(_,Symbol lt))

  • bool isRelType(Symbol::\rel(_))

  • bool isRelType(Symbol::\set(Symbol tp))

  • default bool isRelType(Symbol _)

Synopsis

Determine if the given type is a relation.

1.16.40. isListRelType

Function
  • bool isListRelType(Symbol::\alias(,,Symbol at))

  • bool isListRelType(Symbol::\parameter(_,Symbol tvb))

  • bool isListRelType(Symbol::\label(_,Symbol lt))

  • bool isListRelType(Symbol::\lrel(_))

  • bool isListRelType(Symbol::\list(Symbol tp))

  • default bool isListRelType(Symbol _)

Synopsis

Determine if the given type is a list relation.

1.16.41. isTupleType

Function
  • bool isTupleType(Symbol::\alias(,,Symbol at))

  • bool isTupleType(Symbol::\parameter(_,Symbol tvb))

  • bool isTupleType(Symbol::\label(_,Symbol lt))

  • bool isTupleType(Symbol::\tuple(_))

  • default bool isTupleType(Symbol _)

Synopsis

Determine if the given type is a tuple.

1.16.42. isListType

Function
  • bool isListType(Symbol::\alias(,,Symbol at))

  • bool isListType(Symbol::\parameter(_,Symbol tvb))

  • bool isListType(Symbol::\label(_,Symbol lt))

  • bool isListType(Symbol::\list(_))

  • bool isListType(Symbol::\lrel(_))

  • default bool isListType(Symbol _)

Synopsis

Determine if the given type is a list.

1.16.43. isListRelType

Function
  • bool isListRelType(Symbol::\alias(,,Symbol at))

  • bool isListRelType(Symbol::\parameter(_,Symbol tvb))

  • bool isListRelType(Symbol::\label(_,Symbol lt))

  • bool isListRelType(Symbol::\lrel(_))

  • default bool isListRelType(Symbol _)

Synopsis

Determine if the given type is a list relation.

1.16.44. isMapType

Function
  • bool isMapType(Symbol::\alias(,,Symbol at))

  • bool isMapType(Symbol::\parameter(_,Symbol tvb))

  • bool isMapType(Symbol::\label(_,Symbol lt))

  • bool isMapType(Symbol::\map(,))

  • default bool isMapType(Symbol _)

Synopsis

Determine if the given type is a map.

1.16.45. isBagType

Function
  • bool isBagType(Symbol::\alias(,,Symbol at))

  • bool isBagType(Symbol::\parameter(_,Symbol tvb))

  • bool isBagType(Symbol::\label(_,Symbol lt))

  • bool isBagType(Symbol::\bag(_))

  • default bool isBagType(Symbol _)

Synopsis

Determine if the given type is a bag (bags are not yet implemented).

1.16.46. isADTType

Function
  • bool isADTType(Symbol::\alias(,,Symbol at))

  • bool isADTType(Symbol::\parameter(_,Symbol tvb))

  • bool isADTType(Symbol::\label(_,Symbol lt))

  • bool isADTType(Symbol::\adt(,))

  • bool isADTType(Symbol::\reified(_))

  • default bool isADTType(Symbol _)

Synopsis

Determine if the given type is an Abstract Data Type (ADT).

1.16.47. isConstructorType

Function
  • bool isConstructorType(Symbol::\alias(,,Symbol at))

  • bool isConstructorType(Symbol::\parameter(_,Symbol tvb))

  • bool isConstructorType(Symbol::\label(_,Symbol lt))

  • bool isConstructorType(Symbol::\cons(Symbol _,str _,list[Symbol] _))

  • default bool isConstructorType(Symbol _)

Synopsis

Determine if the given type is a constructor.

1.16.48. isAliasType

Function
  • bool isAliasType(Symbol::\alias(,,_))

  • bool isAliasType(Symbol::\parameter(_,Symbol tvb))

  • bool isAliasType(Symbol::\label(_,Symbol lt))

  • default bool isAliasType(Symbol _)

Synopsis

Determine if the given type is an alias.

1.16.49. isFunctionType

Function
  • bool isFunctionType(Symbol::\alias(,,Symbol at))

  • bool isFunctionType(Symbol::\parameter(_,Symbol tvb))

  • bool isFunctionType(Symbol::\label(_,Symbol lt))

  • bool isFunctionType(Symbol::\func(,,_))

  • bool isFunctionType(Symbol::\func(,))

  • default bool isFunctionType(Symbol _)

Synopsis

Determine if the given type is a function.

1.16.50. isReifiedType

Function
  • bool isReifiedType(Symbol::\alias(,,Symbol at))

  • bool isReifiedType(Symbol::\parameter(_,Symbol tvb))

  • bool isReifiedType(Symbol::\label(_,Symbol lt))

  • bool isReifiedType(Symbol::\reified(_))

  • default bool isReifiedType(Symbol _)

Synopsis

Determine if the given type is a reified type.

1.16.51. isTypeVar

Function
  • bool isTypeVar(Symbol::\parameter(,))

  • bool isTypeVar(Symbol::\alias(,,Symbol at))

  • bool isTypeVar(Symbol::\label(_,Symbol lt))

  • default bool isTypeVar(Symbol _)

Synopsis

Determine if the given type is an type variable (parameter).

1.17. ValueIO

Usage

import ValueIO;

Synopsis

Library functions for reading and writing values in textual and binary format.

1.17.1. readValueFile

Function

value readValueFile(loc file)

Synopsis

Read a value from a binary file in PBF format.

1.17.2. getFileLength

Function

int getFileLength(loc file)

Synopsis

Get length of a file in number of bytes.

1.17.3. readBinaryValueFile

Function
  • &T readBinaryValueFile(type[&T] result, loc file)

  • value readBinaryValueFile(loc file)

Synopsis

Read a typed value from a binary file.

1.17.4. readTextValueFile

Function
  • &T readTextValueFile(type[&T] result, loc file)

  • value readTextValueFile(loc file)

Synopsis

Read a typed value from a text file.

1.17.5. readTextValueFileWithEmbeddedTypes

Function

&T readTextValueFileWithEmbeddedTypes(type[&T] result, loc file)

Synopsis

If you have written a file containing reified types, then you can use this function to read them back.

1.17.6. readTextValueString

Function
  • value readTextValueString(str input)

  • &T readTextValueString(type[&T] result, str input)

Synopsis

Parse a textual string representation of a value.

1.17.7. writeBinaryValueFile

Function

void writeBinaryValueFile(loc file, value val, bool compression = true)

Synopsis

Write a value to a file using an efficient binary file format.

1.17.8. writeTextValueFile

Function

void writeTextValueFile(loc file, value val)

Synopsis

Write a value to a file using a textual file format.

2. analysis

Synopsis

Library functions for analysis tasks.

Description
  • FCA: Library for Formal Concept Analysis.

  • graphs: Analyzing unlabeled and labelled graphs.

    • Graph: A Graph datatype with associated functions.

    • LabeledGraph: Return the bottom nodes of a LGraph.

  • m3: a language independent meta model for facts about source code, which is extensible to include language specific modeling elements.

  • statistics: Statistical functions.

2.1. FCA

Usage

import analysis::formalconcepts::FCA;

Synopsis

Library for Formal Concept Analysis

Description

Formal Concept Analysis is a somewhat ubiquitous tool in software analysis projects. It can be used to find latent groups of objects that share the same attributes in a dataset. Typically, we apply FCA to a relation rel[&O objects, &A attributes], which represents extracted source code artifacts and their attributes.

[[FCA-FormalContext[&Object, &Attribute]]] ## FormalContext[&Object, &Attribute] .Types rel[&Object, &Attribute]

[[FCA-Concept[&Object, &Attribute]]] ## Concept[&Object, &Attribute] .Types tuple[set[&Object] objects, set[&Attribute] attributes]

[[FCA-ConceptLattice[&Object, &Attribute]]] ## ConceptLattice[&Object, &Attribute] .Types rel[Concept[&Object, &Attribute], Concept[&Object, &Attribute]]

[[FCA-Object2Attributes[&Object, &Attribute]]] ## Object2Attributes[&Object, &Attribute] .Types map[&Object, set[&Attribute]]

[[FCA-Attribute2Objects[&Attribute, &Object]]] ## Attribute2Objects[&Attribute, &Object] .Types map[&Attribute, set[&Object]]

2.1.1. fca

Function

ConceptLattice[&Object, &Attribute] fca (FormalContext[&Object, &Attribute] fc)

Synopsis

Computes Concept Lattice given the Object Attribute Relation.

2.1.2. toDot

Function
  • DotGraph toDot(ConceptLattice[&Object, &Attribute] cl)

  • DotGraph toDot(ConceptLattice[&Object, &Attribute] cl, bool lab)

Synopsis

Computes Dot Graph from Concept Lattice.

2.1.3. toDotline

Function

Dotline toDotline(ConceptLattice[&Object, &Attribute] cl)

2.1.4. toOutline

Function

Outline toOutline(ConceptLattice[&Object, &Attribute] cl)

2.1.5. toFormalContext

Function
  • FormalContext[&Object, &Attribute] toFormalContext(Object2Attributes[&Object, &Attribute] objects)

  • FormalContext[&Object, &Attribute] toFormalContext(Attribute2Objects[&Object, &Attribute] attributes)

2.1.6. intersection

Function

set[&T] intersection(set[set[&T]] st)

2.1.7. union

Function

set[&T] union(set[set[&T]] st)

2.1.8. isSubset

Function

bool isSubset(set[set[&T]] candidate, set[&T] s )

2.1.9. sigma

Function

set[&Attribute] sigma(FormalContext[&Object, &Attribute] fc, set[&Object] objects)

2.1.10. tau

Function

set[&Object] tau(FormalContext[&Object, &Attribute] fc, set[&Attributes] attributes)

2.1.11. maxincl

Function

set[set[&T]] maxincl(set[set[&T]] c)

2.1.12. createAttributeLattice

Function

rel[set[&Attribute], set[&Attribute]] createAttributeLattice(FormalContext[&Object, &Attribute] fc)

2.1.13. makeNodes

Function

map[Concept[&Object, &Attribute], int] makeNodes(ConceptLattice[&Object, &Attribute] q)

2.1.14. newAdded1

Function

set[&Attribute] newAdded1(ConceptLattice[&Object, &Attribute] q, Concept[&Object, &Attribute] c)

2.1.15. newAdded0

Function

set[Concept[&Object, &Attribute]] newAdded0(ConceptLattice[&Object, &Attribute] q, Concept[&Object, &Attribute] c)

2.1.16. compose

Function

Stm compose(Concept[&Object, &Attribute] c, map[Concept[&Object, &Attribute], int] z, bool lab)

2.1.17. toDotString

Function

str toDotString(ConceptLattice[&Object, &Attribute] q)

Synopsis

Write relation in .dot format.

2.2. graphs

Synopsis

Analyzing unlabeled and labelled graphs.

Description

Graphs are represented as relations. So in general the idea is to use the Relation module to manipulate graphs. At the same time there are algorithms and analyses which make particular sense when we view a relation as a graph, hence the existence of the Graph and LabeledGraph libraries.

  • Graph: A Graph datatype with associated functions.

  • LabeledGraph: Return the bottom nodes of a LGraph.

2.2.1. Graph

Usage

import analysis::graphs::Graph;

Synopsis

A Graph datatype with associated functions.

Types

alias Graph[&T] = rel[&T from, &T to];

Description

The Graph data type is a binary relation and all operators and functions defined on relations are also defined on Graphs.

The Graph library provides the following functions:

  • Graph[&T]:

  • order: Compute topological order of the nodes in a graph.

  • stronglyConnectedComponents: Compute strongly connected components in a graph.

  • stronglyConnectedComponentsAndTopSort:

  • bottom: Determine the bottom nodes (leaves) of a graph.

  • predecessors: Determine the direct predecessors of a graph node.

  • reach: Determine the graph nodes reachable from a set of nodes.

  • reachR: Determine the graph nodes reachable from a set of nodes using a restricted set of intermediate nodes.

  • reachX: Determine the graph nodes reachable from a set of nodes excluding certain intermediate nodes.

  • shortestPathPair: Determine the shortest path between two graph nodes.

  • successors: Determine the direct successors of a graph node.

  • top: Determine the set of top nodes (roots) of a graph.

  • connectedComponents: Determine the connected components of a graph.

[[Graph-Graph[&T]]] ## Graph[&T] .Types rel[&T from, &T to]

order
Function

list[&T] order(Graph[&T] g)

Synopsis

Compute topological order of the nodes in a graph.

Examples
rascal>import  analysis::graphs::Graph;
ok
rascal>order({<3,4>, <1,2>, <2,4>, <1,3>});
list[int]: [1,2,3,4]
stronglyConnectedComponents
Function

set[set[&T]] stronglyConnectedComponents(Graph[&T] g)

Synopsis

Compute strongly connected components in a graph.

Examples
rascal>import  analysis::graphs::Graph;
ok
rascal>stronglyConnectedComponents({<1, 2>, <2, 3>, <3, 2>, <2, 4>, <4, 2>, <3, 5>, <5, 3>, <4, 5>, <5, 3>});
set[set[int]]: {
  {1},
  {5,3,2,4}
}
stronglyConnectedComponentsAndTopSort
Function

tuple[set[set[&T]], list[&T]] stronglyConnectedComponentsAndTopSort(Graph[&T] g)

bottom
Function

set[&T] bottom(Graph[&T] G)

Synopsis

Determine the bottom nodes (leaves) of a graph.

Description

Returns the bottom nodes of Graph G, i.e., the leaf nodes that don’t have any descendants.

Examples
rascal>import analysis::graphs::Graph;
ok
rascal>bottom({<1,2>, <1,3>, <2,4>, <3,4>});
set[int]: {4}
predecessors
Function

set[&T] predecessors(Graph[&T] G, &T From)

Synopsis

Determine the direct predecessors of a graph node.

Description

Returns the direct predecessors of node From in Graph G.

Examples
rascal>import analysis::graphs::Graph;
ok
rascal>predecessors({<1,2>, <1,3>, <2,4>, <3,4>}, 4);
set[int]: {3,2}
reach
Function

set[&T] reach(Graph[&T] G, set[&T] Start)

Synopsis

Determine the graph nodes reachable from a set of nodes.

Description

Returns the set of nodes in Graph G that are reachable from any of the nodes in the set Start.

reachR
Function

set[&T] reachR(Graph[&T] G, set[&T] Start, set[&T] Restr)

Synopsis

Determine the graph nodes reachable from a set of nodes using a restricted set of intermediate nodes.

Description

Returns the set of nodes in Graph G that are reachable from any of the nodes in set Start using path that only use nodes in the set Restr.

Examples
rascal>import analysis::graphs::Graph;
ok
rascal>reachR({<1,2>, <1,3>, <2,4>, <3,4>}, {1}, {1, 2, 3});
set[int]: {3,2}
reachX
Function

set[&T] reachX(Graph[&T] G, set[&T] Start, set[&T] Excl)

Synopsis

Determine the graph nodes reachable from a set of nodes excluding certain intermediate nodes.

Description

Returns set of nodes in Graph G that are reachable from any of the nodes in Start via path that exclude nodes in Excl.

Examples
rascal>import analysis::graphs::Graph;
ok
rascal>reachX({<1,2>, <1,3>, <2,4>, <3,4>}, {1}, {2});
set[int]: {3,4}
shortestPathPair
Function

list[&T] shortestPathPair(Graph[&T] G, &T From, &T To)

Synopsis

Determine the shortest path between two graph nodes.

Description

Returns the shortest path between nodes From and To in Graph G.

successors
Function

set[&T] successors(Graph[&T] G, &T From)

Synopsis

Determine the direct successors of a graph node.

Description

Returns the direct successors of node From in Graph G.

Examples
rascal>import analysis::graphs::Graph;
ok
rascal>successors({<1,2>, <1,3>, <2,4>, <3,4>}, 1);
set[int]: {3,2}
top
Function

set[&T] top(Graph[&T] G)

Synopsis

Determine the set of top nodes (roots) of a graph.

Description

Returns the top nodes of Graph G, i.e., the root nodes that do not have any predecessors.

Examples
rascal>import analysis::graphs::Graph;
ok
rascal>top({<1,2>, <1,3>, <2,4>, <3,4>});
set[int]: {1}
connectedComponents
Function

set[set[&T]] connectedComponents(Graph[&T] G)

Synopsis

Determine the connected components of a graph.

Description

Returns the connected components of Graph G, as sets of nodes. All nodes within one component are all reachable from one another, there are no paths between two nodes from different components. The graph is assumed to be undirected.

Examples
rascal>import analysis::graphs::Graph;
ok
rascal>connectedComponents({<1,2>, <1,3>, <4,5>, <5,6>});
set[set[int]]: {
  {5,4,6},
  {1,3,2}
}

2.2.2. LabeledGraph

Usage

import analysis::graphs::LabeledGraph;

[[LabeledGraph-LGraph[&T,&L]]] ## LGraph[&T,&L] .Types rel[&T from, &L label, &T to]

bottom
Function

set[&T] bottom(LGraph[&T,&L] G)

Synopsis

Return the bottom nodes of a LGraph.

predecessors
Function

set[&T] predecessors(LGraph[&T,&L] G, &T From)

Synopsis

The predecessors of a single node in a LGraph.

reach
Function

set[&T] reach(LGraph[&T,&L] G, set[&T] Start)

Synopsis

Reachability from a given start set of nodes.

reachR
Function

set[&T] reachR(LGraph[&T,&L] G, set[&T] Start, set[&T] Restr)

Synopsis

Reachability from given start set of nodes with restrictions.

reachX
Function

set[&T] reachX(LGraph[&T,&L] G, set[&T] Start, set[&T] Excl)

Synopsis

Reachability from given start set of nodes with exclusions.

successors
Function

set[&T] successors(LGraph[&T, &L] G, &T From)

Synopsis

The successors of a single node in a LGraph.

top
Function

set[&T] top(LGraph[&T,&L] G)

Synopsis

Return the top nodes of a LGraph.

2.3. m3

Synopsis

a language independent meta model for facts about source code, which is extensible to include language specific modeling elements

Description
this documentation awaits adaptation of m3 with the Rascal compiler

This is the core language independent model:

  • M3: the m3 constructor is identified by the name of a project encoded as a [$Expressions/Values/Location] and has annotations for each kind of fact extracted from a project.

For language-specific support, please go here:

  • [lang/java/m3]

To get started with m3 immediately, please have a look at:

  • [$lang/java/jdt/m3/Core/createM3FromEclipseProject]

Examples
  • See [$Recipes:Metrics/MeasuringJava] for a step-by-step by-example recipe for how to use M3 for measuring things about Java:

2.4. statistics

Synopsis

Statistical functions.

Description

A collection of statistical functions based on the Apache statistics library.

We do not provide a course on (or even an introduction to) statistics. Useful background information can be found here:

The following functionality is offered:

Pitfalls
  • Be aware that in creating data for statistical analysis, repeated values may occur. This implies that you should avoid creating sets of observations. This also explains why the functions provided here take lists (with elements of various types) as argument.

  • The validity of several of the statistics depend on the assumption that the observations included in the model are drawn from a Bivariate Normal Distribution. This is explicitly stated for functions this is the case.

The statistics library is still highly experimental. Interfaces may change and functions maybe added or deleted without notice.

2.4.1. Correlation

Usage

import analysis::statistics::Correlation;

Synopsis

Correlation between data values.

Description

Compute the correlation between pairs of data values. Correlation measures the statistical relationship between two sets of data.

The following functions are provided:

PearsonsCorrelation
Function

num PearsonsCorrelation(lrel[num x,num y] values)

Synopsis

Pearson product-moment correlation coefficient.

Description

Compute the Pearson product-moment correlation coefficient. It is a measure of the strength of the linear dependence between two variables.

Pitfalls

Use SpearmansCorrelation when there is a monotonous dependence between the two variables.

PearsonsCorrelationStandardErrors
Function

list[real] PearsonsCorrelationStandardErrors(lrel[num x,num y] values)

Synopsis

Standard errors associated with Pearson correlation.

PearsonsCorrelationPValues
Function

list[real] PearsonsCorrelationPValues(lrel[num x,num y] values)

Synopsis

P-values (significance) associated with Pearson correlation.

SpearmansCorrelation
Function

num SpearmansCorrelation(lrel[num x,num y] values)

Synopsis

Spearman’s rank correlation coefficient.

Description

Compute Spearman’s rank correlation coefficient. The correlation between the data values is computed by first performing a rank transformation on the data values using a natural ranking and then computing PearsonsCorrelation.

Pitfalls

Use PearsonsCorrelation when there is a linear dependence between the variables.

covariance
Function

num covariance(lrel[num x,num y] values)

Synopsis

Covariance of data values.

Description

Computes the covariance between the x and y values.

Examples
rascal>import analysis::statistics::Correlation;
ok
rascal>covariance([<1,12>,<3,12>,<3,11>,<5,7>]);
num: -2.5

2.4.2. Descriptive

Usage

import analysis::statistics::Descriptive;

Synopsis

Descriptive Statistics.

Description

Provides the following univariate (single variable) statistics functions:

Examples
rascal>import analysis::statistics::Descriptive;
ok
rascal>D = [67, 88, 55, 92.5, 102, 51];
list[num]: [67,88,55,92.5,102,51]
rascal>mn = min(D);
num: 51
rascal>mx = max(D);
num: 102
rascal>range = mx - mn;
num: 51
rascal>midrange =  mn + range/2;
num: 76.5
rascal>sum(D);
num: 455.5
rascal>mean(D);
real: 75.91666667
rascal>geometricMean(D);
real: 73.3734107237
rascal>standardDeviation(D);
real: 21.1622698845
rascal>variance(D);
num: 447.841666666666666666666666666
rascal>percentile(D,25);
num: 55
rascal>percentile(D,50);
num: 67
rascal>percentile(D,75);
num: 92.5
geometricMean
Function
  • real geometricMean(list[num] l:[])

  • default real geometricMean([num hd, *num tl])

kurtosis
Function

real kurtosis(list[num] values)

Synopsis

Kurtosis of data values.

Description

Computes the kurtosis of the given data values. Kurtosis is a measure of the "peakedness" of a distribution.

kurtosisExcess
Function

real kurtosisExcess(list[num] values)

Synopsis

Kurtosis excess of data values.

Description

Computes the kurtosis excess of the given data values. Kurtosis excess is a measure of the "peakedness" of a distribution corrected such that a normal distribution will be 0.

max
Function

(&T <: num) max(list[&T <: num] nums) throws EmptyList

Synopsis

Largest data value.

mean
Function
  • real mean(list[&T<:num] l:[])

  • default real mean(list[num] nums)

median
Function
  • real median(list[num] l:[])

  • default real median(list[num] nums)

middle
Function

list[&T] middle(list[&T] nums)

min
Function

(&T <: num) min(list[&T <: num] nums) throws EmptyList

Synopsis

Smallest data value.

percentile
Function

&T <: num percentile(list[&T <: num] nums, num p)

Synopsis

Percentile of data values.

Description

Returns the p`th percentile of the data values. 0 < `p ⇐ 100 should hold.

variance
Function
  • num variance(list[num] l:[])

  • num variance([num hd, *num tl])

skewness
Function
  • real skewness(list[num] l:[])

  • default real skewness(list[num] values)

standardDeviation
Function

real standardDeviation(list[num] values)

Synopsis

Standard deviation of data values.

Description

Computes the standard deviation of the data values. It shows how much variation exists from the average (mean, or expected value).

sum
Function
  • (&T <:num) sum(list[(&T <:num)] _:[])

  • default (&T <:num) sum([(&T <: num) hd, *(&T <: num) tl])

sumsq
Function

(&T <:num) sumsq(list[&T <:num] values)

Synopsis

Sum of the squares of data values.

centralMoment
Function

real centralMoment(list[num] nums, int order = 1)

Calculate the k-th central moment

moment
Function

real moment(list[num] nums, int order = 1)

Calculate the k-th moment

size
Function

int size(list[&T] lst)

tail
Function

list[&T] tail(list[&T] lst) throws EmptyList

head
Function

&T head(list[&T] lst) throws EmptyList

sort
Function
  • list[&T] sort(list[&T] lst)

  • list[&T] sort(list[&T] l, bool (&T a, &T b) less)

2.4.3. Frequency

Usage

import analysis::statistics::Frequency;

Synopsis

Frequency distributions.

Description

Counting the frequency of events is usually the first step in statistical analysis of raw data. It involves choosing what are the events to count, how to group them in certain categories and then quickly counting the frequency of each occurring event.

This module helps by providing commonly used functions for the purpose of counting events. The output of these functions can be used to draw (cumulative) histograms, or they can directly be used for further statistical processing and visualisation.

distribution
Function
  • map[&T, int] distribution(rel[&U event, &T bucket] input)

  • map[&T <: num, int] distribution(rel[&U event, &T <: num bucket] input, &T <: num bucketSize)

  • map[&T, int] distribution(map[&U event, &T bucket] input)

  • map[&T <: num, int] distribution(map[&U event, &T <: num bucket] input, &T <: num bucketSize)

Synopsis

Compute a distribution: count how many times events are mapped to which bucket.

Examples
rascal>import analysis::statistics::Frequency;
ok
rascal>distribution({<"chicken","animal">,<"bear","animal">,<"oak","plant">,<"tulip","plant">});
map[str, int]: ("plant":2,"animal":2)
rascal>distribution({<"alice",2>,<"bob",3>,<"claire",5>},5);
map[int, int]: (5:2,0:1)
cumFreq
Function
  • int cumFreq(list[value] values, num n)

  • int cumFreq(list[value] values, str s)

Synopsis

Cumulative frequency of values less than or equal to a given value.

Description

Returns the cumulative frequency of values less than or equal to a given numeric or string value. Returns 0 if the value is not comparable to the values set.

Examples
rascal>import analysis::statistics::Frequency;
ok
rascal>D = [1, 2, 1, 1, 3, 5];
list[int]: [1,2,1,1,3,5]
rascal>cumFreq(D, 1);
int: 3
rascal>cumFreq(D, 2);
int: 4
rascal>cumFreq(D, 10);
int: 6
cumPct
Function
  • num cumPct(list[value] values, num n)

  • num cumPct(list[value] values, str s)

Synopsis

Cumulative percentage of values less than or equal to a given value.

Description

Returns the cumulative percentage of values less than or equal to v (as a proportion between 0 and 1).

rascal>import analysis::statistics::Frequency;
ok
rascal>D = [1, 2, 1, 1, 3, 5];
list[int]: [1,2,1,1,3,5]
rascal>cumPct(D, 1);
num: 0.5
rascal>cumPct(D, 2);
num: 0.6666666666666666
rascal>cumPct(D, 10);
num: 1.0
pct
Function
  • num pct(list[value] values, num n)

  • num pct(list[value] values, str s)

Synopsis

Percentage of values that are equal to a given value.

Description

Returns the percentage of values that are equal to v (as a proportion between 0 and 1). .Examples

rascal>import analysis::statistics::Frequency;
ok
rascal>D = [1, 2, 1, 1, 3, 5];
list[int]: [1,2,1,1,3,5]
rascal>pct(D, 1);
num: 0.5
rascal>pct(D, 2);
num: 0.16666666666666666
rascal>pct(D, 10);
num: 0.0

2.4.4. Inference

Usage

import analysis::statistics::Inference;

Synopsis

Statistical inference methods.

Description

The following functions are provided:

chiSquare
Function

num chiSquare(lrel[num expected, int observed] values)

Synopsis

Chi-square coefficient of data values.

Description

Compute the ChiSquare statistic comparing observed and expected frequency counts.

Examples

Consider an example from the web page mentioned above. To test the hypothesis that a random sample of 100 people has been drawn from a population in which men and women are equal in frequency, the observed number of men and women would be compared to the theoretical frequencies of 50 men and 50 women. If there were 44 men in the sample and 56 women, then we have the following:

rascal>import analysis::statistics::Inference;
ok
rascal>chiSquare([<50, 44>, <50, 56>])
num: 1.44
chiSquareTest
Function
  • num chiSquareTest(lrel[num expected, int observed] values)

  • bool chiSquareTest(lrel[num expected, int observed] values, real alpha)

Synopsis

Chi-square test on data values.

Description

Perform a Chi-square test comparing expected and observed frequency counts. There are two forms of this test:

  • Returns the observed significance level, or p-value, associated with a Chi-square goodness of fit test comparing observed frequency counts to expected counts.

  • Performs a Chi-square goodness of fit test evaluating the null hypothesis that the observed counts conform to the frequency distribution described by the expected counts, with significance level alpha (0 < alpha < 0.5). Returns true iff the null hypothesis can be rejected with confidence 1 - alpha.

tTest
Function
  • num tTest(list[num] sample1, list[num] sample2)

  • bool tTest(list[num] sample1, list[num] sample2, num alpha)

  • bool tTest(num mu, list[num] sample, num alpha)

Synopsis

T-test on sample data.

Description

Perform student’s t-test. The test is provided in three variants:

  • Returns the observed significance level, or p-value, associated with a two-sample, two-tailed t-test comparing the means of the input samples. The number returned is the smallest significance level at which one can reject the null hypothesis that the two means are equal in favor of the two-sided alternative that they are different. For a one-sided test, divide the returned value by 2.

The t-statistic used is t = (m1 - m2) / sqrt(var1/n1 + var2/n2) where

  • n1 is the size of the first sample

  • n2 is the size of the second sample;

  • m1 is the mean of the first sample;

  • m2 is the mean of the second sample;

  • var1 is the variance of the first sample;

  • var2 is the variance of the second sample.

    • Performs a two-sided t-test evaluating the null hypothesis that sample1 and sample2 are drawn from populations with the same mean, with significance level alpha. This test does not assume that the subpopulation variances are equal. Returns true iff the null hypothesis that the means are equal can be rejected with confidence 1 - alpha. To perform a 1-sided test, use alpha / 2.

    • Performs a two-sided t-test evaluating the null hypothesis that the mean of the population from which sample is drawn equals mu. Returns true iff the null hypothesis can be rejected with confidence 1 - alpha. To perform a 1-sided test, use alpha * 2.

Examples

We use the data from the following example to illustrate the t-test. First, we compute the t-statistic using the formula given above.

rascal>import util::Math;
ok
rascal>import analysis::statistics::Descriptive;
ok
rascal>import List;
ok
rascal>s1 = [5,7,5,3,5,3,3,9];
list[int]: [5,7,5,3,5,3,3,9]
rascal>s2 = [8,1,4,6,6,4,1,2];
list[int]: [8,1,4,6,6,4,1,2]
rascal>(mean(s1) - mean(s2))/sqrt(variance(s1)/size(s1) + variance(s2)/size(s2));
real: 0.84731854581

This is the same result as obtained in the cited example. We can also compute it directly using the tTest functions:

rascal>import analysis::statistics::Inference;
ok
rascal>tTest(s1, s2);
num: 0.4115203997374087

Observe that this is a smaller value than comes out directly of the formula. Recall that: The number returned is the smallest significance level at which one can reject the null hypothesis that the two means are equal in favor of the two-sided alternative that they are different. Finally, we perform the test around the significance level we just obtained:

rascal>tTest(s1,s2,0.40);
bool: false
rascal>tTest(s1,s2,0.50);
bool: true
anovaFValue
Function

num anovaFValue(list[list[num]] categoryData)

Synopsis

Analysis of Variance (ANOVA) f-value.

Description

Perform Analysis of Variance test also described here.

Compute the F statistic — also known as F-test — using the definitional formula F = msbg/mswg where

  • msbg = between group mean square.

  • mswg = within group mean square.

are as defined here.

anovaPValue
Function

num anovaPValue(list[list[num]] categoryData)

Synopsis

Analysis of Variance (ANOVA) p-value.

Description

Perform Analysis of Variance test also described here.

Computes the exact p-value using the formula p = 1 - cumulativeProbability(F) where F is the anovaFValue.

anovaTest
Function

bool anovaTest(list[list[num]] categoryData, num alpha)

Synopsis

Analysis of Variance (ANOVA) test.

Description

Perform Analysis of Variance test also described here.

Returns true iff the estimated p-value is less than alpha (0 < alpha ⇐ 0.5).

The exact p-value is computed using the formula p = 1 - cumulativeProbability(F) where F is the anovaFValue.

gini
Function

real gini(lrel[num observation,int frequency] values)

Synopsis

Gini coefficient.

Description

Computes the Gini coefficient that measures the inequality among values in a frequency distribution.

The Gini coefficient is computed using Deaton’s formula and returns a value between 0 (completely equal distribution) and 1 (completely unequal distribution).

Examples
rascal>import analysis::statistics::Inference;
ok

A completely equal distribution:

rascal>gini([<10000, 1>, <10000, 1>, <10000, 1>]);
real: 0.0

A rather unequal distribution:

rascal>gini([<998000, 1>, <20000, 3>, <117500, 1>, <70000, 2>, <23500, 5>, <45200,1>]);
real: 0.8530758129256304

2.4.5. SimpleRegression

Usage

import analysis::statistics::SimpleRegression;

Synopsis

Statistical methods for simple regression.

Description

The following functions are provided:

intercept
Function

num intercept(lrel[num,num] values) throws IllegalArgument

Synopsis

Intercept of regression line. .Description

Returns the intercept of the estimated regression line. The least squares estimate of the intercept is computed using these normal equations.

interceptStdErr
Function

num interceptStdErr(lrel[num,num] values) throws IllegalArgument

Synopsis

Standard error of intercept estimate. .Description Returns the standard error of the intercept estimate, usually denoted s(b0).

meanSquareError
Function

num meanSquareError(lrel[num,num] values) throws IllegalArgument

Synopsis

Sum of squared errors divided by the degrees of freedom.

Description

Returns the sum of squared errors divided by the degrees of freedom, usually abbreviated MSE.

R
Function

num R(lrel[num,num] values) throws IllegalArgument

Synopsis

Pearson’s product-moment correlation coefficient.

Description

Computes Pearson’s product-moment correlation coefficient. More functions related to this coefficient can be found in Correlation.

regressionSumSquares
Function

num regressionSumSquares(list[tuple[num,num]] values) throws IllegalArgument

Synopsis

Sum of squared deviations of the predicted y values about their mean.

Description

Returns the sum of squared deviations of the predicted y values about their mean (which equals the mean of y). This is usually abbreviated SSR or SSM.

RSquare
Function

num RSquare(lrel[num,num] values) throws IllegalArgument

Synopsis

Coefficient of determination. .Description

Returns the coefficient of determination usually denoted r__2. It provides a measure of how well future outcomes are likely to be predicted by the regression model.

significance
Function

num significance(lrel[num,num] values) throws IllegalArgument

Synopsis

Significance of the slope correlation. .Description

Returns the significance level of the slope (equiv) correlation. Specifically, the returned value is the smallest alpha such that the slope confidence interval with significance level equal to alpha does not include 0. On regression output, this is often denoted Prob(|t| > 0)

Pitfalls

The validity of this statistic depends on the assumption that the observations included in the model are drawn from a Bivariate Normal Distribution.

slope
Function

num slope(lrel[num,num] values) throws IllegalArgument

Synopsis

Slope of regression line. .Description Returns the slope of the estimated regression line. The least squares estimate of the slope is computed using the normal equations. The slope is sometimes denoted b1.

slopeConfidenceInterval
Function

num slopeConfidenceInterval(lrel[num,num] values) throws IllegalArgument

Synopsis

The 95% slope confidence interval.

Description

Returns the half-width of a 95% confidence interval for the slope estimate. The 95% confidence interval is

(slope - slopeConfidenceInterval, slope + slopeConfidenceInterval)

Pitfalls

The validity of this statistic depends on the assumption that the observations included in the model are drawn from a Bivariate Normal Distribution.

slopeStdErr
Function

num slopeStdErr(lrel[num,num] values) throws IllegalArgument

Synopsis

Standard error of slope estimate. .Description

Returns the standard error of the slope estimate, usually denoted s(b1).

sumOfCrossProducts
Function

num sumOfCrossProducts(lrel[num,num] values) throws IllegalArgument

Synopsis

Sum of cross products of observations. .Description

Returns the sum of crossproducts, xi*yi.

sumSquaredErrors
Function

num sumSquaredErrors(lrel[num,num] values) throws IllegalArgument

Synopsis

Sum of squared errors. .Description

Returns the sum of squared errors (SSE) associated with the regression model. The sum is computed using the computational formula

SSE = SYY - (SXY * SXY / SXX)

where SYY is the sum of the squared deviations of the y values about their mean, SXX is similarly defined and SXY is the sum of the products of x and y mean deviations.

The return value is constrained to be non-negative, i.e., if due to rounding errors the computational formula returns a negative result, 0 is returned.

totalSumSquares
Function

num totalSumSquares(lrel[num,num] values) throws IllegalArgument

Synopsis

Sum of squared deviations. .Description

Returns the sum of squared deviations of the y values about their mean. This is defined as SSTO.

XSumSquares
Function

num XSumSquares(lrel[num,num] values) throws IllegalArgument

Synopsis

Sum of squared deviations of x values about their mean.

Description

Returns the sum of squared deviations of the x values about their mean.

predict
Function

num predict(lrel[num,num] values, num x) throws IllegalArgument

Synopsis

Predict a value. .Description

Returns the "predicted" y value associated with the supplied x value, based on regression model derived from the provided data values:

predict(x) = intercept + slope * x

3. lang

Synopsis

Definitions and tools for various languages.

Description
  • RSF: Functions for reading/writing the Rigi Standard Format (RSF).

    • readRSF: Read a file in Rigi Standard Format (RSF).

  • csv: Comma-Separated Values (CSV).

  • java: Definitions and tools related to the Java language.

    • jdt: tools for Java provided via reusing the Eclipse JDT.

    • m3: Java-specific version of the M3 model.

  • xml: XML utilities.

3.1. RSF

Synopsis

Functions for reading/writing the Rigi Standard Format (RSF).

Usage

import lang::RSF::IO;

Description

Rigi Standard Format (RSF) is a textual format to represent binary relations and is used to exchange relational facts between different tools.

An RSF file consists of triples of the form

$RelName$ $Elem_1$ $Elem_2$

where RelName is the name of a relation and Elem1 and Elem2 are element values.

Provides the following function:

  • readRSF: Read a file in Rigi Standard Format (RSF).

Examples
call    main          printf
call    main          listcreate
data    main          FILE
data    listcreate    List

defines two relations named call and data.

3.1.1. readRSF

Synopsis

Read a file in Rigi Standard Format (RSF).

Function

map[str, rel[str,str]] readRSF(str nameRSFFile) throws IO(str msg)

Description

Since an RSF file may define more than one relation, a mapping from relation name to relation value is returned.

Examples

For the RSF file:

call    main          printf
call    main          listcreate
data    main          FILE
data    listcreate    List

readRSF will create the following map:

("call" : {<"main", "printf">, <"main", "listcreate">},
 "data" : {<"main", "FILE">, <"listcreate", "List">})

3.2. csv

Synopsis

Comma-Separated Values (CSV).

Description

The CSV format was originally intended for exchanging information between spreadsheets and databases but is today used as an exchange format in many other application domains as well. A CSV file has the following structure:

  • An optional header line consisting of field names separated by comma’s.

  • One or more lines consisting of values separated by comma’s.

Some adaptation is possible and includes:

  • Including or excluding the header line (use "header" : "true" in the option map for the various functions).

  • Using another separator than a comma (use "separator" : ";" in the option map for the various functions, where ";" can be any single character string).

The following functions are provided in the [Rascal-Libraries-lang-csv-IO] library:

Examples

Here is an example CSV file using the default separator (","):

field_name1,field_name2,field_name3
aaa,bbb,ccc
zzz,yyy,xxx

Here is an example CSV file using a non-default separator (";"):

position;artist;title;year
1;Eagles;Hotel California;1977
2;Queen;Bohemian rhapsody;1975
3;Boudewijn de Groot;Avond;1997

3.3. java

Synopsis

Definitions and tools related to the Java language.

3.3.1. jdt

Synopsis

tools for Java provided via reusing the Eclipse JDT

m3
Synopsis

functions for generating M3 models starting from Eclipse projects

3.3.2. m3

Synopsis

Java-specific version of the M3 model

Description

This API extends m3 with Java specific functionality:

Use this API to extract Java m3 models starting from Eclipse Java projects:

AST
Usage

import lang::java::m3::AST;

Synopsis

defines AST node types for Java

Declaration
Types
data Declaration
     = \compilationUnit(list[Declaration] imports, list[Declaration] types)
     | \compilationUnit(Declaration package, list[Declaration] imports, list[Declaration] types)
     | \enum(str name, list[Type] implements, list[Declaration] constants, list[Declaration] body)
     | \enumConstant(str name, list[Expression] arguments, Declaration class)
     | \enumConstant(str name, list[Expression] arguments)
     | \class(str name, list[Type] extends, list[Type] implements, list[Declaration] body)
     | \class(list[Declaration] body)
     | \interface(str name, list[Type] extends, list[Type] implements, list[Declaration] body)
     | \field(Type \type, list[Expression] fragments)
     | \initializer(Statement initializerBody)
     | \method(Type \return, str name, list[Declaration] parameters, list[Expression] exceptions, Statement impl)
     | \method(Type \return, str name, list[Declaration] parameters, list[Expression] exceptions)
     | \constructor(str name, list[Declaration] parameters, list[Expression] exceptions, Statement impl)
     | \import(str name)
     | \package(str name)
     | \package(Declaration parentPackage, str name)
     | \variables(Type \type, list[Expression] \fragments)
     | \typeParameter(str name, list[Type] extendsList)
     | \annotationType(str name, list[Declaration] body)
     | \annotationTypeMember(Type \type, str name)
     | \annotationTypeMember(Type \type, str name, Expression defaultBlock)
     | \parameter(Type \type, str name, int extraDimensions)
     | \vararg(Type \type, str name)
     ;
Expression
Types
data Expression
     = \arrayAccess(Expression array, Expression index)
     | \newArray(Type \type, list[Expression] dimensions, Expression init)
     | \newArray(Type \type, list[Expression] dimensions)
     | \arrayInitializer(list[Expression] elements)
     | \assignment(Expression lhs, str operator, Expression rhs)
     | \cast(Type \type, Expression expression)
     | \characterLiteral(str charValue)
     | \newObject(Expression expr, Type \type, list[Expression] args, Declaration class)
     | \newObject(Expression expr, Type \type, list[Expression] args)
     | \newObject(Type \type, list[Expression] args, Declaration class)
     | \newObject(Type \type, list[Expression] args)
     | \qualifiedName(Expression qualifier, Expression expression)
     | \conditional(Expression expression, Expression thenBranch, Expression elseBranch)
     | \fieldAccess(bool isSuper, Expression expression, str name)
     | \fieldAccess(bool isSuper, str name)
     | \instanceof(Expression leftSide, Type rightSide)
     | \methodCall(bool isSuper, str name, list[Expression] arguments)
     | \methodCall(bool isSuper, Expression receiver, str name, list[Expression] arguments)
     | \null()
     | \number(str numberValue)
     | \booleanLiteral(bool boolValue)
     | \stringLiteral(str stringValue)
     | \type(Type \type)
     | \variable(str name, int extraDimensions)
     | \variable(str name, int extraDimensions, Expression \initializer)
     | \bracket(Expression expression)
     | \this()
     | \this(Expression thisExpression)
     | \super()
     | \declarationExpression(Declaration declaration)
     | \infix(Expression lhs, str operator, Expression rhs)
     | \postfix(Expression operand, str operator)
     | \prefix(str operator, Expression operand)
     | \simpleName(str name)
     | \markerAnnotation(str typeName)
     | \normalAnnotation(str typeName, list[Expression] memberValuePairs)
     | \memberValuePair(str name, Expression \value)
     | \singleMemberAnnotation(str typeName, Expression \value)
     ;
Statement
Types
data Statement
     = \assert(Expression expression)
     | \assert(Expression expression, Expression message)
     | \block(list[Statement] statements)
     | \break()
     | \break(str label)
     | \continue()
     | \continue(str label)
     | \do(Statement body, Expression condition)
     | \empty()
     | \foreach(Declaration parameter, Expression collection, Statement body)
     | \for(list[Expression] initializers, Expression condition, list[Expression] updaters, Statement body)
     | \for(list[Expression] initializers, list[Expression] updaters, Statement body)
     | \if(Expression condition, Statement thenBranch)
     | \if(Expression condition, Statement thenBranch, Statement elseBranch)
     | \label(str name, Statement body)
     | \return(Expression expression)
     | \return()
     | \switch(Expression expression, list[Statement] statements)
     | \case(Expression expression)
     | \defaultCase()
     | \synchronizedStatement(Expression lock, Statement body)
     | \throw(Expression expression)
     | \try(Statement body, list[Statement] catchClauses)
     | \try(Statement body, list[Statement] catchClauses, Statement \finally)
     | \catch(Declaration exception, Statement body)
     | \declarationStatement(Declaration declaration)
     | \while(Expression condition, Statement body)
     | \expressionStatement(Expression stmt)
     | \constructorCall(bool isSuper, Expression expr, list[Expression] arguments)
     | \constructorCall(bool isSuper, list[Expression] arguments)
     ;
Type
Types
data Type
     = arrayType(Type \type)
     | parameterizedType(Type \type)
     | qualifiedType(Type qualifier, Expression simpleName)
     | simpleType(Expression typeName)
     | unionType(list[Type] types)
     | wildcard()
     | upperbound(Type \type)
     | lowerbound(Type \type)
     | \int()
     | short()
     | long()
     | float()
     | double()
     | char()
     | string()
     | byte()
     | \void()
     | \boolean()
     ;
Modifier
Types
data Modifier
     = \private()
     | \public()
     | \protected()
     | \friendly()
     | \static()
     | \final()
     | \synchronized()
     | \transient()
     | \abstract()
     | \native()
     | \volatile()
     | \strictfp()
     | \annotation(Expression \anno)
     | \onDemand()
     | \default()
     ;
getPaths
Function

set[loc] getPaths(loc dir, str suffix)

findRoots
Function

set[loc] findRoots(set[loc] folders)

createAstFromFile
Function

Declaration createAstFromFile(loc file, bool collectBindings, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")

Synopsis

Creates AST from a file

createAstsFromFiles
Function

set[Declaration] createAstsFromFiles(set[loc] file, bool collectBindings, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")

Synopsis

Creates AST from a file

createAstFromString
Function

Declaration createAstFromString(loc fileName, str source, bool collectBinding, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")

Creates ASTs from an input string

createAstsFromDirectory
Function

set[Declaration] createAstsFromDirectory(loc project, bool collectBindings, bool errorRecovery = false, str javaVersion = "1.7" )

Creates ASTs from a project

Core
Usage

import lang::java::m3::Core;

Synopsis

extends the M3 [$analysis/m3/Core] with Java specific concepts such as inheritance and overriding.

Description

For a quick start, go find [createM3FromEclipseProject].

M3
Types
data M3 (
	rel[loc from, loc to] extends = {},            // classes extending classes and interfaces extending interfaces
	rel[loc from, loc to] implements = {},         // classes implementing interfaces
	rel[loc from, loc to] methodInvocation = {},   // methods calling each other (including constructors)
	rel[loc from, loc to] fieldAccess = {},        // code using data (like fields)
	rel[loc from, loc to] typeDependency = {},     // using a type literal in some code (types of variables, annotations)
	rel[loc from, loc to] methodOverrides = {},    // which method override which other methods
	rel[loc declaration, loc annotation] annotations = {}
)
Language
Types
data Language (str version="")
     = java()
     ;
composeJavaM3
Function

M3 composeJavaM3(loc id, set[M3] models)

diffJavaM3
Function

M3 diffJavaM3(loc id, list[M3] models)

createM3FromFile
Function

M3 createM3FromFile(loc file, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")

createM3sFromFiles
Function

set[M3] createM3sFromFiles(set[loc] files, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")

createM3FromFiles
Function

M3 createM3FromFiles(loc projectName, set[loc] files, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")

createM3sAndAstsFromFiles
Function

tuple[set[M3], set[Declaration]] createM3sAndAstsFromFiles(set[loc] files, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")

createM3FromString
Function

M3 createM3FromString(loc fileName, str contents, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")

createM3FromJarClass
Function

M3 createM3FromJarClass(loc jarClass, list[loc] classPath = [])

createM3FromSingleClass
Function

M3 createM3FromSingleClass(loc jarClass, str className)

createM3FromJarFile
Function

M3 createM3FromJarFile(loc jarLoc, list[loc] classPath = [])

createM3FromDirectory
Function

M3 createM3FromDirectory(loc project, bool errorRecovery = false, str javaVersion = "1.7", list[loc] classPath = [])

Synopsis

globs for jars, class files and java files in a directory and tries to compile all source files into an [$analysis/m3] model

createM3FromJar
Function

M3 createM3FromJar(loc jarFile, list[loc] classPath = [])

unregisterJavaProject
Function

void unregisterJavaProject(loc project)

getMethodSignature
Function

str getMethodSignature(loc method)

isCompilationUnit
Function

bool isCompilationUnit(loc entity)

isPackage
Function

bool isPackage(loc entity)

isClass
Function

bool isClass(loc entity)

isConstructor
Function

bool isConstructor(loc entity)

isMethod
Function

bool isMethod(loc entity)

isParameter
Function

bool isParameter(loc entity)

isVariable
Function

bool isVariable(loc entity)

isField
Function

bool isField(loc entity)

isInterface
Function

bool isInterface(loc entity)

isEnum
Function

bool isEnum(loc entity)

isType
Function

bool isType(loc entity)

files
Function

set[loc] files(rel[loc, loc] containment)

declaredMethods
Function

rel[loc, loc] declaredMethods(M3 m, set[Modifier] checkModifiers = {})

declaredFields
Function

rel[loc, loc] declaredFields(M3 m, set[Modifier] checkModifiers = {})

declaredFieldsX
Function

rel[loc, loc] declaredFieldsX(M3 m, set[Modifier] checkModifiers = {})

declaredTopTypes
Function

rel[loc, loc] declaredTopTypes(M3 m)

declaredSubTypes
Function

rel[loc, loc] declaredSubTypes(M3 m)

classes
Function

set[loc] classes(M3 m)

interfaces
Function

set[loc] interfaces(M3 m)

packages
Function

set[loc] packages(M3 m)

variables
Function

set[loc] variables(M3 m)

parameters
Function

set[loc] parameters(M3 m)

fields
Function

set[loc] fields(M3 m)

methods
Function

set[loc] methods(M3 m)

constructors
Function

set[loc] constructors(M3 m)

enums
Function

set[loc] enums(M3 m)

types
Function

set[loc] types(M3 m)

elements
Function

set[loc] elements(M3 m, loc parent)

fields
Function

set[loc] fields(M3 m, loc class)

methods
Function

set[loc] methods(M3 m, loc class)

constructors
Function

set[loc] constructors(M3 m, loc class)

nestedClasses
Function

set[loc] nestedClasses(M3 m, loc class)

<AUTOINSERTED>

typeDependency
Types
anno rel[loc from, loc to] M3@typeDependency;
Usage

</AUTOINSERTED>

TypeHierarchy
Usage

import lang::java::m3::TypeHierarchy;

getDeclaredTypeHierarchy
Function

rel[loc from, loc to] getDeclaredTypeHierarchy(M3 model)

TypeSymbol
Usage

import lang::java::m3::TypeSymbol;

Bound
Types
data Bound
     = \super(list[TypeSymbol] bound)
     | \extends(list[TypeSymbol] bound)
     | \unbounded()
     ;
TypeSymbol
Types
data TypeSymbol
     = \class(loc decl, list[TypeSymbol] typeParameters)
     | \interface(loc decl, list[TypeSymbol] typeParameters)
     | \enum(loc decl)
     | \method(loc decl, list[TypeSymbol] typeParameters, TypeSymbol returnType, list[TypeSymbol] parameters)
     | \constructor(loc decl, list[TypeSymbol] parameters)
     | \typeParameter(loc decl, Bound upperbound)
     | \typeArgument(loc decl)
     | \wildcard(Bound bound)
     | \capture(Bound bound, TypeSymbol wildcard)
     | \intersection(list[TypeSymbol] types)
     | \union(list[TypeSymbol] types)
     | \object()
     | \int()
     | \float()
     | \double()
     | \short()
     | \boolean()
     | \char()
     | \byte()
     | \long()
     | \void()
     | \null()
     | \array(TypeSymbol component, int dimension)
     | \typeVariable(loc decl)
     | \unresolved()
     ;
subtype
Function

default bool subtype(TypeSymbol s, TypeSymbol t)

lub
Function

default TypeSymbol lub(TypeSymbol s, TypeSymbol t)

3.4. xml

Synopsis

XML utilities

Description

XML is a widely used markup language for encoding and exchanging documents.

The following functions and datatypes are provided, all based on the Document Object Model (DOM):

4. util

Synopsis

Utilities: functions, data types and interfaces with external libraries.

Description
  • Benchmark: Functions for time measurement and benchmarking.

  • Clipboard:

  • Eval: Evaluate a (list of) Rascal commands and return the value of the last command.

  • Math: Mathematical functions.

  • Monitor: Monitor the progress of a task/job.

  • PriorityQueue: A PriorityQueue datatype and associated functions.

  • Prompt:

  • Resources: A Resource datatype and related functions on Eclipse resources.

    • dependencies: Compute the (transitive) dependencies of a project.

    • getProject: Retrieve the hierarchical representation of a single named project.

    • projects: Retrieve the set of project locations of the current Eclipse workspace.

    • references: The set of projects that are referenced by a project.

    • root: Retrieve a full hierarchical representation of all resources in the Eclipse workspace.

  • ShellExec: Execute and manage external processes.

4.1. Benchmark

Usage

import util::Benchmark;

Synopsis

Functions for time measurement and benchmarking.

Description

The Benchmark library provides the following functions:

4.1.1. heapDump

Function

void heapDump(loc file, bool live=true)

Synopsis

Write a JVM heap dump to a file.

Description
  • The file parameter has to be of the file scheme.

  • The live parameter restricts the dump to only live objects.

4.1.2. cpuTime

Function
  • int cpuTime()

  • int cpuTime(void () block)

Synopsis

CPU time in nanoseconds (10-9 sec).

Description
  • Current cpu time in nanoseconds (10-9 sec) since the start of the thread that runs the code that calls this function.

  • The cpu time in nanoseconds used by the execution of the code block.

Examples

We use the fac function described in Factorial as example:

rascal>import util::Benchmark;
ok
rascal>import demo::basic::Factorial;
ok

Here we measure time by using separate calls to cpuTime before and after a call to fac.

rascal>before = cpuTime();
int: 52262941321
rascal>fac(50);
int: 30414093201713378043612608166064768844377641568960512000000000000
rascal>cpuTime() - before;
int: 1232618

The code to be measured can also be passed as a function parameter to cpuTime:

rascal>cpuTime( void() { fac(50); } );
int: 217769

These two timings for the same task may differ significantly due to the way these statements are executed here in the tutor.

4.1.3. systemTime

Function
  • int systemTime()

  • int systemTime(void () block)

Synopsis

System time in nanoseconds (10-9 sec).

Description
  • Current system time in nanoseconds (10-9 sec) since the start of the thread that runs the code that calls this function.

  • System time in nanoseconds needed to execute the code block.

Examples

We use the fac function described in Factorial as example:

rascal>import util::Benchmark;
ok
rascal>import demo::basic::Factorial;
ok

Here we measure time by using separate calls to sytemTime before and after a call to fac.

rascal>before = systemTime();
int: 1283634911
rascal>fac(50);
int: 30414093201713378043612608166064768844377641568960512000000000000
rascal>systemTime() - before;
int: 1319819

The code to be measured can also be passed as a function parameter to systemTime:

rascal>systemTime( void() { fac(50); } );
int: 250865

4.1.4. userTime

Function
  • int userTime()

  • int userTime(void () block)

Synopsis

User time in nanoseconds (10-9 sec).

Description
  • Current time in nanoseconds (10-9 sec) since the start of the thread that runs the code that calls this function.

  • User time in nanoseconds needed to execute the code block.

Examples

We use the fac function described in Factorial as example:

rascal>import util::Benchmark;
ok
rascal>import demo::basic::Factorial;
ok

Here we measure time by using separate calls to userTime before and after a call to fac.

rascal>before = userTime();
int: 51020000000
rascal>fac(50);
int: 30414093201713378043612608166064768844377641568960512000000000000
rascal>userTime() - before;
int: 10000000

The code to be measured can also be passed as a function parameter to userTime:

rascal>userTime( void() { fac(50); } );
int: 0

4.1.5. realTime

Function
  • int realTime()

  • int realTime(void () block)

Synopsis

Current time in milliseconds (10-3 sec).

Description
  • Current system time in milliseconds (10-3 sec) since January 1, 1970 GMT.

  • Real time in milliseconds needed to execute the code block.

Pitfalls

This function is a competitor for the now function that provides a datetime value for the current time.

4.1.6. benchmark

Function
  • map[str,num] benchmark(map[str, void()] Cases)

  • map[str,num] benchmark(map[str, void()] Cases, int (void ()) duration)

Synopsis

Measure and report the execution time of name:void-closure pairs

Description

Given is a map that maps strings (used as label to identify each case) to void-closures that execute the code to be benchmarked. An optional duration argument can be used to specify the function to perform the actual measurement. By default the function realTime is used. A map of labels and durations is returned.

Examples

We use the fac function described in Factorial as example:

rascal>import util::Benchmark;
ok
rascal>import demo::basic::Factorial;
ok

We measure two calls to the factorial function with arguments 100, respectively, 200 (using by default realTime that returns milliseconds):

rascal>benchmark( ("fac100" : void() {fac(100);}, "fac200" : void() {fac(200);}) );
map[str, num]: ("fac100":0,"fac200":1)

We can do the same using userTime that returns nanoseconds:

rascal>benchmark( ("fac100" : void() {fac(100);}, "fac200" : void() {fac(200);}), userTime );
map[str, num]: ("fac100":0,"fac200":0)

4.1.7. getNanoTime

Function

int getNanoTime()

Synopsis

Current time in nanoseconds (10-9 sec) since January 1, 1970 GMT. .Description

4.1.8. getMilliTime

Function

int getMilliTime()

Synopsis

Current time in milliseconds (10-3 sec) since January 1, 1970 GMT.

Description

This function is a synonym for realTime and gives the wall clock time in milliseconds.

4.1.9. gc

Function

int gc()

Synopsis

Force a garbage collection.

Description

This function forces a garbage collection and can, for instance, be used before running a benchmark.

4.2. Clipboard

documentation awaits Eclipse integration

4.3. Eval

Usage

import util::Eval;

4.3.1. Result

Types
data Result[&T]
     = ok()
     | result(&T val)
     ;

4.3.2. Exception

Types
data Exception
     = StaticError(str message, loc location)
     ;

4.3.3. eval

Function
  • Result[&T] eval(type[&T] typ, str command) throws Timeout, StaticError, ParseError

  • Result[value] eval(str command)

  • Result[&T] eval(type[&T] typ, list[str] commands) throws Timeout, StaticError, ParseError

  • Result[value] eval(list[str] commands)

  • Result[&T] eval(type[&T] typ, str command, int duration) throws Timeout, StaticError, ParseError

  • Result[value] eval(str command, int duration)

  • Result[&T] eval(type[&T] typ, list[str] commands, int duration) throws Timeout, StaticError, ParseError

  • Result[value] eval(list[str] commands, int duration)

Synopsis

Evaluate a (list of) Rascal commands and return the value of the last command.

Description

Evaluate a command or a list of commands and return the value of the last command that is executed.

Note that a command can be one of:

  • Statement

  • Declaration

  • Import

  • Extend

  • SyntaxDefinition

The notable exclusion are [Expressions]. An Expression is not allowed as a command to the eval function. You can easily make a Statement from an Expression by adding a semi-colon.

An optional duration argument may be present to limit the time (in milliseconds) the execution may take. By default, the duration is set to 1000 ms.

Examples
rascal>import util::Eval;
ok
rascal>eval("2 * 3;");
Result[value]: result(6)
rascal>eval(["X = 2 * 3;", "X + 5;"]);
Result[value]: result(11)

4.3.4. evalType

Function
  • str evalType(str command) throws Timeout, StaticError, ParseError

  • str evalType(list[str] commands) throws Timeout, StaticError, ParseError

  • str evalType(str command, int duration) throws Timeout, StaticError, ParseError

  • str evalType(list[str] commands, int duration) throws Timeout, StaticError, ParseError

Synopsis

Evaluate a (list of) Rascal commands and return the type of the last command.

Description

Evaluate a command or a list of commands and return the type of the value of the last command that is executed. An optional duration argument may be present to limit the time (in milliseconds) the execution may take. By default, the duration is set to 1000 ms.

Examples
rascal>import util::Eval;
ok
rascal>evalType("2 * 3;");
str: "int"
rascal>evalType("[1, 2, 3];");
str: "list[int]"

4.3.5. unimport

Function

void unimport(str muduleName)

4.4. Math

Usage

import util::Math;

Synopsis

Mathematical functions.

Description

The Math library provides the following functions:

  • abs: Absolute value of a number.

  • arbInt: Generate a random integer value.

  • arbInt:

  • arbReal: Generate a random real value in the interval [0.0,1.0).

  • arbSeed: Define the seed for the generation of arbitrary values.

  • arbRat: Generate an arbitrary rational value.

  • arbRat:

  • ceil: Compute the smallest integer that is larger than a given number.

  • cos: Calculate the cosine of a numeric value.

  • denominator: Return the denominator of a rational value

  • E: The constant E.

  • exp: Compute exp(x).

  • floor: Compute the largest integer that is smaller than a given number.

  • ln: Calculate the natural log of a numeric value.

  • log: Calculate the log<sub>base</sub> of a numeric value.

  • log10: Compute the 10 based log(x)

  • log2: Compute the 2 based log(x)

  • max: Determine the largest of two numeric values.

  • min: Determine the smallest of two numeric values.

  • numerator: Return the numerator of a rational value

  • nroot: Calculate the n<sup>th</sup> root of a numeric value.

  • PI: The constant pi.

  • pow: Calculate an arbitrary power of a numeric value.

  • pow: Calculate an arbitrary power of a numeric value.

  • precision: Return the precision of a real number

  • precision: Return a real number with given precisio

  • setPrecision: Define the precision for numeric calculations; returns the previous precision

  • scale: Return the scale of a real number

  • unscaled: Return the unscaled integer of a real

  • remainder: Return the remainder of dividing the numerator by the denominator

  • round: Round a number to the nearest multiple of a given number (default 1).

  • round:

  • fitFloat: .Synopsis push real value into a float using coercion and return the value represented by that float as a real

  • fitDouble: .Synopsis push real value into a JVM double using coercion and return the value represented by that float as a real

  • percent: Compute the ratio between two numbers as a percentage.

  • sin: Calculate the sine of a numeric value.

  • sqrt: Calculate the square root of a numeric value.

  • tan: Calculate the tangent of a numeric value.

  • toInt: Convert a numeric value to an integer.

  • toRat: Convert two numbers to a rational value (not supported on reals)

  • toReal: Convert a numeric value to a real.

  • toString: Convert a numeric value to a string.

  • primes: generate prime numbers up to a maximu

  • arbPrime:

4.4.1. abs

Function

&T <: num abs(&T <: num N)

Synopsis

Absolute value of a number.

Description

Absolute value of the number n. The result type is equal to the type of the argument n.

Examples
rascal>import util::Math;
ok
rascal>abs(13)
int: 13
rascal>abs(-13)
int: 13
rascal>abs(3.14)
real: 3.14
rascal>abs(-3.14)
real: 3.14

4.4.2. arbInt

Function
  • int arbInt()

  • int arbInt(int limit)

Synopsis

Generate a random integer value.

Description

Return an arbitrary integer value. When the argument limit is given, the generated value is in the interval [0, limit), i.e., the limit is exclusive.

Examples
rascal>import util::Math;
ok
rascal>arbInt();
int: 2120775180
rascal>arbInt();
int: 1413509092
rascal>arbInt();
int: -1951235994
rascal>arbInt(10);
int: 0
rascal>arbInt(10);
int: 3
rascal>arbInt(10);
int: 4
Benefits

arbInt is a convenient generator for pseudo-random integers.

4.4.3. arbReal

Function

real arbReal()

Synopsis

Generate a random real value in the interval [0.0,1.0).

Description

Generates an arbitrary real value in the interval [0.0, 1.0].

Examples
rascal>import util::Math;
ok
rascal>arbReal();
real: 0.8975683413571618
rascal>arbReal();
real: 0.2606163777622995
rascal>arbReal();
real: 0.8004021397281109

4.4.4. arbSeed

Function

void arbSeed(int seed)

Synopsis

Define the seed for the generation of arbitrary values.

Description

Define the seed for the generation of arbitrary values such as arbBool, arbInt, arbReal, arbRat, getOneFrom,getOneFrom, takeOneFrom and takeOneFrom. arbSeed resets the random number generator that is used to choose arbitrary values. This can be used to generate a reproducible series of choices.

4.4.5. arbRat

Function
  • rat arbRat()

  • rat arbRat(int limit1, int limit2)

Synopsis

Generate an arbitrary rational value.

Examples
rascal>import util::Math;
ok
rascal>arbRat();
rat: -242229896r310779733
rascal>arbRat();
rat: 778141191r1901301140
rascal>arbRat();
rat: 1859499173r1660916611
rascal>arbRat(10,100);
rat: 7r41
rascal>arbRat(10,100);
rat: 9r82
rascal>arbRat(10,100);
rat: 1r

4.4.6. ceil

Function

int ceil(num x)

Synopsis

Compute the smallest integer that is larger than a given number.

Description

Computes the ceiling of a given number. Also see floor.

Examples
rascal>import util::Math;
ok
rascal>ceil(3.2);
int: 4
rascal>ceil(-3.2);
int: -3

4.4.7. cos

Function

real cos(num x)

Synopsis

Calculate the cosine of a numeric value.

Description

The cosine of the number x.

Examples
rascal>import util::Math;
ok
rascal>cos(1.0)
real: 0.54030230588
rascal>cos(60 * PI() / 180)
real: 0.50000000000

4.4.8. denominator

Function

int denominator(rat n)

Synopsis

Return the denominator of a rational value.

4.4.9. E

Function

real E()

Synopsis

The constant E.

Examples
rascal>import util::Math;
ok
rascal>E();
real: 2.7182818285

4.4.10. exp

Function

real exp(num x)

Synopsis

Compute exp(x). .Description Calculate e<sup>`x`</sup>.

4.4.11. floor

Function

int floor(num x)

Synopsis

Compute the largest integer that is smaller than a given number.

Description

Computes the floor of a given number. Also see ceil.

Examples
rascal>import util::Math;
ok
rascal>floor(3.2);
int: 3
rascal>floor(-3.2);
int: -4

4.4.12. ln

Function

real ln(num x)

Synopsis

Calculate the natural log of a numeric value.

Description

Calculate natural log of x.

Examples
rascal>import util::Math;
ok
rascal>ln(20.0)
real: 2.9957322736
rascal>ln(42.0)
real: 3.7376696183

4.4.13. log

Function

real log(num x, num base)

Synopsis

Calculate the log<sub>base</sub> of a numeric value.

Description

Calculate log<sub>base</sub> of x.

Examples
rascal>import util::Math;
ok
rascal>log(9.99999999, 10)
real: 0.999999999566
rascal>log(10, 10)
real: 1.
rascal>log(256.0, 2)
real: 7.99999999999

4.4.14. log10

Function

real log10(num x)

Synopsis

Compute the 10 based log(x).

4.4.15. log2

Function

real log2(num x)

Synopsis

Compute the 2 based log(x).

4.4.16. max

Function

&T <: num max(&T <: num N, &T <: num M)

Synopsis

Determine the largest of two numeric values.

Description

The largest of two numbers. The type of the result is the same as the type of the largest argument.

Examples
rascal>import util::Math;
ok
rascal>max(12, 13);
int: 13
rascal>max(12, 13.5);
num: 13.5
rascal>max(12, 11.5);
num: 12

4.4.17. min

Function

&T <: num min(&T <: num N, &T <: num M)

Synopsis

Determine the smallest of two numeric values.

Description

The smallest of two numbers. The type of the result is the same as the type of the smallest argument.

Examples
rascal>import util::Math;
ok
rascal>min(12, 13);
int: 12
rascal>min(12, -13);
int: -13
rascal>min(3.14, 4);
num: 3.14

4.4.18. numerator

Function

int numerator(rat n)

Synopsis

Return the numerator of a rational value.

4.4.19. nroot

Function

real nroot(num x, int n)

Synopsis

Calculate the n<sup>th</sup> root of a numeric value.

Description

Calculate <sup>n</sup>√`x` where n can only be a integer.

Examples
rascal>import util::Math;
ok
rascal>nroot(42 * 42, 2);
real: 42.0000000000
rascal>nroot(42 * 42 * 42, 3);
real: 42.0000000000
rascal>nroot(123456789012345678901234567890123456789.0, 100)
real: 2.4038930938

4.4.20. PI

Function

real PI()

Synopsis

The constant pi.

Examples
rascal>import util::Math;
ok
rascal>PI();
real: 3.1415926536

4.4.21. pow

Function
  • real pow(num x, int y)

  • real pow(num x, real y)

Synopsis

Calculate an arbitrary power of a numeric value.

Description

The calculate x<sup>`y`</sup> where y can only be a integer.

Examples
rascal>import util::Math;
ok
rascal>pow(sqrt(42), 2)
real: 41.99999999989811976256
rascal>pow(12345678901234567890.0, 1000)
real: 327323519862176629730082067574716643439462300540185122220961832511288805718030910484304325108222843885957688250811158315340566475836232001571619541935415038796348602192296984423155079801992333140052863080750492018420590783574245411031311510942905796189450351912614510641741094491709589411239576756065619918176653289948094430880732479266853021246187981170634861333302200580872985856560855518977488511675544145006801675791138351985746678734387422142342185164278661836498313416561398901718399810114596984172777042303963800096899625199810241300878005585014082782334502894938457546968837522885101157892509894692459561354313786780532679517827353604060468681961209174542267424246240853816845886755294209996435433895294269712878992262721644106226890031664370462222706979715904672586297266460593551184450504665032451235999357222433465060299295477020462819514888057483551478759508444976793225466736775132290553092049866427876353526626065630474037490603570383940996843823967040247622022658439400707006053650592894261198654836654639504753542843560398908885522596433160079097075880850067383018892541529465995345763588872837837593907229770700976597566733884202506653739605059379401347861288230399126563406134764726379055786459406660737522798066830604288612726394086519909309338994703718119693639450620275447776806553594104597194048560725083279242120977189767528195495335507571774589656293544257012451347889004221446663952536972136269481724663158860532924322053397767933001924701437115740854657082984585991651836842229921223742828990473127280082431920682100750955123993671834387994643422520721282979578784909325571258649149109201827243509225859052305726449746668735118920743230654106301983770403775061147939915240771494456634249374454345250552415101593382958143513116801567849013973694567642919070533812941570184136127617255991655186770210261385873186409485713856293174509996217914589400976889855958713421577335212662218393411619879901532201876563269347123972872344497080886637930441651259141049569049804413000150297629676129305940405487092640315363913091042956266173352666027423873096773031569220441623779694026871629405544513139993091183726122490006827751752741076885620415211542317496941956676394754879276979814511653516542017832996653484412313736356363305261532812972679430377759838879013873699720739033015759349473652785594888893377041014822677972342113818352300626995374712448170130314174419289739529982021437898597025566184922042135782017301373340541840251886826793222171028600662975155228812797443522045892690780164900156894217461209188361915847649443941189447229439906721259825215932223371314915787322490148065038149065584317884221248098894972346389635965334847844894296983317214252456367600733903894880305858451738209033898028888738089429510748290579293786966511702526421636839023818144487303883796157019333481281590182592242664434310787411848124503254182702718762286778744163663752419726010543539695902378784425822053579035604233167402979429162902604120869094779466506794967733027126798330733504515320709935121379216936936503517150761677018393050209847312382660928887004146016965681452309940614395990071269237730777211494402285973401134347314396249658064535813498390390228707068969712346028221844247394911352355219205653068923998044169246696199205931532280062594043451189765555574643899576685276356280338555983266720699445887933479778575910620051014501087647914152552526207935492180262761720164698382158135451840846941977075240573647713026577508324564964050461276723248623764128711424186543354565805827986611623687766424190141159982065651733888853975873295262987666051724164426176971670664220786382312628833993735024432664073367706606256513404081195840674289520710497921821809284330939220609778362882454615392304832328664341446921914422579024146155571399642339764786384745922769575752043854715925941119782659099976703423673050490970007943369522561413084390356583974592565338819090682096052094155857739238468257491510074355659857818999361006574913097067978865657382215313176814231120597124842183478696513677197512045290255088756641096724459645973492430801864900314570449211289319281689687528990384602371132230192221449626569380251208…​

4.4.22. precision

Function
  • int precision(num x)

  • real precision(num x, int p)

Synopsis

Return the precision of a real number.

4.4.23. setPrecision

Function

int setPrecision(int p)

Synopsis

Define the precision for numeric calculations; returns the previous precision.

4.4.24. scale

Function

int scale(num x)

Synopsis

Return the scale of a real number.

4.4.25. unscaled

Function

int unscaled(real x)

Synopsis

Return the unscaled integer of a real.

4.4.26. remainder

Function

int remainder(rat n)

Synopsis

Return the remainder of dividing the numerator by the denominator.

4.4.27. round

Function
  • int round(num d)

  • (&T <: num) round(&T <: num r, &T <: num nearest)

Synopsis

Round a number to the nearest multiple of a given number (default 1).

Examples
rascal>import util::Math;
ok
rascal>round(3.4);
int: 3
rascal>round(3.5);
int: 4
rascal>round(3.6);
int: 4
rascal>round(-3.4);
int: -3
rascal>round(-3.5);
int: -4
rascal>round(-3.6);
int: -4
rascal>round(13, 5);
int: 15
rascal>round(1.5,0.2);
real: 1.6
rascal>round(3r2,1r4);
rat: 3r2

4.4.28. fitFloat

Function

real fitFloat(real r) throws ArithmeticException

Description

The function fitFloat converts the unlimited precision real into a JVM float value.

Benefits
  • This function comes in handy in combination with random real test values which have to go through coercion in a Java library, like so: bool test myTest(real r, real j) = fitFloat(r) + fitFloat(j) == fitFloat(r) + fitFloat(j);

Pitfalls
  • If the real is smaller than the minimum float value or larger than the maximum float value, this function will throw an ArithmeticException.

4.4.29. fitDouble

Function

real fitDouble(real r) throws ArithmeticException

Description

The function fitDouble converts the unlimited precision real into a JVM double value.

Benefits
  • This function comes in handy in combination with random real test values which have to go through coercion in a Java library, like so: bool test myTest(real r, real j) = fitDouble(r) + fitDouble(j) == fitDouble(r) + fitDouble(j);

Pitfalls
  • If the real is smaller than the minimum double value or larger than the maximum double value, this function will throw an ArithmeticException.

4.4.30. percent

Function

int percent(num part, num whole)

Synopsis

Compute the ratio between two numbers as a percentage.

Examples
rascal>import util::Math;
ok
rascal>percent(1r4, 1);
int: 25
rascal>percent(13,250);
int: 5
rascal>percent(80.0,160.0);
int: 50

4.4.31. sin

Function

real sin(num x)

Synopsis

Calculate the sine of a numeric value.

Description

The sine of the number x.

Examples
rascal>import util::Math;
ok
rascal>sin(0)
real: 0.
rascal>sin(PI() / 2)
real: 1.00000000000

4.4.32. sqrt

Function

real sqrt(num x)

Synopsis

Calculate the square root of a numeric value.

Description

Calculate √`x`.

Examples
rascal>import util::Math;
ok
rascal>sqrt(42 * 42);
real: 42.0000000000
rascal>sqrt(12345678901234567890.5 * 12345678901234567890.5);
real: 12345678901234567890.5000000000

4.4.33. tan

Function

real tan(num x)

Synopsis

Calculate the tangent of a numeric value.

Description

The tangent of the number x.

Examples
rascal>import util::Math;
ok
rascal>tan(45 * PI() / 180)
real: 1.0000000000

4.4.34. toInt

Function

int toInt(num N)

Synopsis

Convert a numeric value to an integer.

Description

Convert a number to an integer. If n is an integer, this is the identity. If n is a real value (implemented as BigDecimal) to an integer (implemented as BigInteger). This conversion is analogous to a narrowing primitive conversion from double to long as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded. Note that this conversion can loose information about the precision of the BigDecimal value.

Examples
rascal>import util::Math;
ok
rascal>toInt(13)
int: 13
rascal>toInt(13.5)
int: 13

4.4.35. toRat

Function

rat toRat(int numerator, int denominator)

Synopsis

Convert two numbers to a rational value (not supported on reals).

4.4.36. toReal

Function

real toReal(num N)

Synopsis

Convert a numeric value to a real.

Examples
rascal>import util::Math;
ok
rascal>toReal(12)
real: 12.
rascal>toReal(3.14)
real: 3.14

4.4.37. toString

Function

str toString(num N)

Synopsis

Convert a numeric value to a string.

Examples
rascal>import util::Math;
ok
rascal>toString(12)
str: "12"
rascal>toString(3.14)
str: "3.14"

4.4.38. primes

Function

list[int] primes(int upTo)

Synopsis

generate prime numbers up to a maximum

4.4.39. arbPrime

Function

int arbPrime(int upTo)

4.5. Monitor

Usage

import util::Monitor;

Synopsis

Monitor the progress of a task/job.

4.5.1. startJob

Function
  • void startJob(str name)

  • void startJob(str name, int totalWork)

  • void startJob(str name, int workShare, int totalWork)

Synopsis

Log the start of a job.

Description

The various forms of startJob do the following:

  • Register a job with a name, a default amount of work contributed to the overall task, and an unknown amount of steps to do.

  • Register a job with a name and a total amount of steps to do (this will also be the amount of work contributed to the parent job, if any

  • Register a job with a name, the amount this will contribute to the overall task, and a total amount of steps to do.

4.5.2. event

Function
  • void event(str name)

  • void event(str name, int inc)

  • void event(int inc)

Synopsis

Log the start of an event (it is ended by another event or by endJob).

Description

The various forms of event behave as follows:

  • Log the start of an event.

  • Log the start of an event with the amount of work that will be done when it’s finished. An event is finished when the next event is logged, or when endJob is called.

  • Log the start of an event with the amount of work that will be done when it’s finished. An event is finished when the next event is logged, or when endJob is called.

4.5.3. endJob

Function

int endJob(bool succeeded)

Synopsis

Log the end of a job.

Description

This should always be called once for every startJob, unless an exception is thrown. Returns the amount of work completed for this job (to help in future estimates)

4.5.4. todo

Function

void todo(int work)

Synopsis

Set the estimated remaining work for the current (sub)job.

Description

Set the estimated remaining work for the current (sub)job. The argument work is the amount of work remaining to be done, or 0 for unknown.

4.6. PriorityQueue

Usage

import util::PriorityQueue;

Synopsis

A PriorityQueue datatype and associated functions.

Usage

import util::PriorityQueue;

Description

Priority queues maintain (priority, value) pairs in sorted order. They are implemented using a Binomial Heap. Priority queue are, for instance, used to implement shortest path algorithms.

Provides the following functions:

Pitfalls

Currently, both priority and associated value ("payload") have to be integers. This will be generalized.

4.6.1. BinomialTree

Types
data BinomialTree
     = binomialTree(int priority,            // priority of this tree
                                         int val,                     // payload
                                         int degree,                  // degree of tree
                                         list[BinomialTree] children  // subtrees
                                        )
     ;

4.6.2. addSubTree

Function

BinomialTree addSubTree(BinomialTree p, BinomialTree q)

4.6.3. mergeTree

Function

BinomialTree mergeTree(BinomialTree p, BinomialTree q)

4.6.4. toString

Function

str toString(BinomialTree T)

4.6.5. PriorityQueue

Types
data PriorityQueue
     = priorityQueue(list[BinomialTree] trees,  // trees in the heap
                                   int minIndex               // index of minimal tree
                                  )
     ;

4.6.6. mkPriorityQueue

Function
  • PriorityQueue mkPriorityQueue()

  • PriorityQueue mkPriorityQueue(int priority, int val)

4.6.7. isEmpty

Function

bool isEmpty(PriorityQueue Q)

4.6.8. insertElement

Function

PriorityQueue insertElement(PriorityQueue Q, int priority, int val)

4.6.9. findMinimum

Function

int findMinimum(PriorityQueue Q)

4.6.10. extractMinimum

Function

tuple[int, int, PriorityQueue] extractMinimum(PriorityQueue Q)

4.6.11. toString

Function

str toString(PriorityQueue Q)

4.6.12. add

Function

list[BinomialTree] add(list[BinomialTree] heap, BinomialTree t)

4.6.13. mergeQueue

Function

PriorityQueue mergeQueue(PriorityQueue p, PriorityQueue q)

4.7. Prompt

documentation awaits Eclipse integration

4.8. Resources

Synopsis

A Resource datatype and related functions on Eclipse resources.

Usage

import util::Resources;

Types
data Resource = root(set[Resource] projects)
              | project(loc id, set[Resource] contents)
              | folder(loc id, set[Resource] contents)
              | file(loc id);
Description

The Resource library provides direct access to Eclipse projects and the resources they contain. A Resource is the Rascal representation of an Eclipse project, or a folder or a file in an Eclipse project. In combination with the IO library module, users of the Resources library gain access to the contents of any file that is in an Eclipse project.

Resource is a recursive data-type, where recursion indicates containment, i.e., a folder contains many other resources, a project also contains other resources. The root of an Eclipse workspace also contains other resources, in particular projects.

Each Resource, but the root, has an id field that explains the exact location of the resource.

The schema project that is supported by source locations (see [Values-Location]) gives direct access to Eclipse projects.

The Resource library provides the following:

  • dependencies: Compute the (transitive) dependencies of a project.

  • getProject: Retrieve the hierarchical representation of a single named project.

  • projects: Retrieve the set of project locations of the current Eclipse workspace.

  • references: The set of projects that are referenced by a project.

  • root: Retrieve a full hierarchical representation of all resources in the Eclipse workspace.

Examples

A location that points to a project in the Eclipse workspace named "myProject":

|project://myProject|

A location that points to a file named HelloWorld.java in the src folder of the example-project project in the workspace:

|project://example-project/src/HelloWorld.java|

A location that points to a part of the previous file, namely the first 10 characters on the first line:

|project://example-project/src/HelloWorld.java|(0,10,1,0,1,10)

Assuming that the project |project://example-project| exists in the current workspace, we can get the following:

rascal>import util::Resources;
|prompt:///|(0,23,<1,0>,<1,23>): Could not import module util::Resources: can not find in search path
Advice: |http://tutor.rascal-mpl.org/Errors/Static/ModuleImport/ModuleImport.html|
ok
rascal>getProject(|project://example-project|);
|prompt:///|(0,10,<1,0>,<1,10>): Undeclared variable: getProject
Advice: |http://tutor.rascal-mpl.org/Errors/Static/UndeclaredVariable/UndeclaredVariable.html|
ok

WARNING: unexpected errors in the above SHELL example. Documentation author please fix!

rascal>import util::Resources;
|prompt:///|(0,23,<1,0>,<1,23>): Could not import module util::Resources: can not find in search path
Advice: |http://tutor.rascal-mpl.org/Errors/Static/ModuleImport/ModuleImport.html|
 
ok
rascal>getProject(|project://example-project-which-does-not-exist|);
|prompt:///|(0,10,<1,0>,<1,10>): Undeclared variable: getProject
Advice: |http://tutor.rascal-mpl.org/Errors/Static/UndeclaredVariable/UndeclaredVariable.html|
 
ok
Pitfalls

This library is only available for the Eclipse version of Rascal.

4.8.1. dependencies

Synopsis

Compute the (transitive) dependencies of a project.

Function

set[loc] dependencies(loc project)

Examples

Assuming that the project |project://example-project| exists in the current workspace, we can get the following:

rascal>import util::Resources;
|prompt:///|(0,23,<1,0>,<1,23>): Could not import module util::Resources: can not find in search path
Advice: |http://tutor.rascal-mpl.org/Errors/Static/ModuleImport/ModuleImport.html|
ok
rascal>dependencies(|project://example-project|);
|prompt:///|(0,12,<1,0>,<1,12>): Undeclared variable: dependencies
Advice: |http://tutor.rascal-mpl.org/Errors/Static/UndeclaredVariable/UndeclaredVariable.html|
ok

WARNING: unexpected errors in the above SHELL example. Documentation author please fix! .Benefits

4.8.2. getProject

Synopsis

Retrieve the hierarchical representation of a single named project.

Function

Resource getProject(loc project)

Examples
rascal>import util::Resources;
|prompt:///|(0,23,<1,0>,<1,23>): Could not import module util::Resources: can not find in search path
Advice: |http://tutor.rascal-mpl.org/Errors/Static/ModuleImport/ModuleImport.html|
ok
rascal>getProject(|project://example-project|);
|prompt:///|(0,10,<1,0>,<1,10>): Undeclared variable: getProject
Advice: |http://tutor.rascal-mpl.org/Errors/Static/UndeclaredVariable/UndeclaredVariable.html|
ok

WARNING: unexpected errors in the above SHELL example. Documentation author please fix!

rascal>import util::Resources;
|prompt:///|(0,23,<1,0>,<1,23>): Could not import module util::Resources: can not find in search path
Advice: |http://tutor.rascal-mpl.org/Errors/Static/ModuleImport/ModuleImport.html|
 
ok
rascal>getProject(|project://example-project-which-does-not-exist|);
|prompt:///|(0,10,<1,0>,<1,10>): Undeclared variable: getProject
Advice: |http://tutor.rascal-mpl.org/Errors/Static/UndeclaredVariable/UndeclaredVariable.html|
 
ok

4.8.3. projects

Synopsis

Retrieve the set of project locations of the current Eclipse workspace.

Function

set[loc] projects()

Examples

The following example shows the projects as they existed when this page was generated:

rascal>import util::Resources;
|prompt:///|(0,23,<1,0>,<1,23>): Could not import module util::Resources: can not find in search path
Advice: |http://tutor.rascal-mpl.org/Errors/Static/ModuleImport/ModuleImport.html|
ok
rascal>projects();
|prompt:///|(0,8,<1,0>,<1,8>): Undeclared variable: projects
Advice: |http://tutor.rascal-mpl.org/Errors/Static/UndeclaredVariable/UndeclaredVariable.html|
ok

WARNING: unexpected errors in the above SHELL example. Documentation author please fix! .Benefits

4.8.4. references

Synopsis

The set of projects that are referenced by a project.

Function

set[loc] references(loc project)

4.8.5. root

Synopsis

Retrieve a full hierarchical representation of all resources in the Eclipse workspace.

Function

Resource root()

Examples
rascal>import util::Resources;
|prompt:///|(0,23,<1,0>,<1,23>): Could not import module util::Resources: can not find in search path
Advice: |http://tutor.rascal-mpl.org/Errors/Static/ModuleImport/ModuleImport.html|
ok
rascal>root();
|prompt:///|(0,4,<1,0>,<1,4>): Undeclared variable: root
Advice: |http://tutor.rascal-mpl.org/Errors/Static/UndeclaredVariable/UndeclaredVariable.html|
ok

WARNING: unexpected errors in the above SHELL example. Documentation author please fix! .Benefits

4.9. ShellExec

Usage

import util::ShellExec;

Synopsis

Execute and manage external processes.

4.9.1. createProcess

Function

PID createProcess(str processCommand, loc workingDir=|cwd:///|, list[str] args = [], map[str,str] envVars = ())

Synopsis

Start a new external process. .Description

4.10. Start a new external process.

4.11. Start a new external process in a given working directory.

4.12. Start a new external process with the given arguments.

4.13. Start a new external process with the given arguments in the given working directory.

4.14. Start a new external process with the given environment variables.

4.15. Start a new external process with the given environment variables in the given working directory.

4.16. Start a new external process with the given arguments and environment variables.

4.17. Start a new external process with the given arguments and environment variables in the given working directory.

4.17.1. exec

Function

str exec(str processCommand, loc workingDir=|cwd:///|, list[str] args = [], map[str,str] env = ())

Synopsis

start, run and kill an external process returning its output as a string.

4.17.2. killProcess

Function

void killProcess(PID processId, bool force=false)

Synopsis

Kill a running process, or a zombie process (a process which is not alive yet not killed)

4.17.3. isAlive

Function

bool isAlive(PID processId)

Synopsis

Check whether a process is still alive

4.17.4. isZombie

Function

bool isZombie(PID processId)

Synopsis

Check whether a process is still registered but not actually running anymore. A zombie process may be cleaned up using killProcess.

4.17.5. readFrom

Function

str readFrom(PID processId)

Synopsis

Read from an existing process’s output stream. This is non-blocking.

4.17.6. readWithWait

Function

str readWithWait(PID processId, int wait)

Synopsis

Read from an existing process’s output stream with a given wait timeout. Some processes are a little slower in producing output. The wait is used to give the process some extra time in producing output. This is non-blocking apart from the waiting.

4.17.7. readFromErr

Function

str readFromErr(PID processId)

Synopsis

Read from an existing process’s error output stream. This is non-blocking.

4.17.8. readLineFromErr

Function

str readLineFromErr(PID processId, int wait=200, int maxTries=5)

Synopsis

Read from an existing process’s error output stream. This blocks until a full line is read and waits for one second maximally for this line to appear.

4.17.9. readEntireStream

Function

str readEntireStream(PID processId)

Synopsis

Read the entire stream from an existing process’s output stream. This is blocking.

4.17.10. readEntireErrStream

Function

str readEntireErrStream(PID processId)

Synopsis

Read the entire error stream from an existing process’s output stream. This is blocking.

4.17.11. writeTo

Function

void writeTo(PID processId, str msg)

Synopsis

Write to an existing process’s input stream.

4.17.12. PID

Types

int

Synopsis

Process Identifiers (PID).

Description

A PID is returned by createProcess and is required for any further interaction with the created process.