
The available Rascal libraries.
The libraries described here provide the following functionality:
1. Prelude
The Rascal standard prelude.
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.
This library makes it possible to import all core Rascal functionality with a single import.
-
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
import Boolean;
Library functions for Booleans.
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
bool arbBool()
Return an arbitrary Boolean value.
rascal>import Boolean;
ok
rascal>arbBool();
bool: false
rascal>arbBool();
bool: false
rascal>arbBool();
bool: true
arbInt
is a convenient generator for arbitrary binary choices.
1.1.2. fromString
bool fromString(str s)
Convert the strings "true" or "false" to a bool.
1.1.3. toInt
int toInt(bool b)
Convert a Boolean value to integer.
Maps true
to 1
and false
to 0
.
rascal>import Boolean;
ok
rascal>toInt(true);
int: 1
rascal>toInt(false);
int: 0
1.1.4. toReal
real toReal(bool b)
Convert Boolean value to real.
Maps true
to 1.0
and false
to 0.0
.
rascal>import Boolean;
ok
rascal>toReal(true);
real: 1.0
rascal>toReal(false);
real: 0.0
1.1.5. toString
str toString(bool b)
Convert Boolean value to string.
Maps true
to "true"
and false
to "false"
.
rascal>import Boolean;
ok
rascal>toString(true);
str: "true"
rascal>toString(false);
str: "false"
1.2. Content
import Content;
Content provides access to the content server of the Rascal terminal for viewing interactive HTML output.
1.2.1. Content
data Content
= content(str id, Response (Request) callback)
| content(Response response)
;
Content wraps the HTTP Request/Response API to support interactive visualization types on the terminal [Rascal.REPL].
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
Content html(str html)
Directly serve a static html page
1.2.3. file
Content file(loc src)
Directly serve the contents of a file
1.2.4. text
Content text(str text)
Directly serve the contents of a string as plain text
1.2.5. Body
value (type[value] expected)
1.2.6. Request
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)
;
Request values represent what a browser is asking for, most importantly the URL path.
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.
-
Note that
put
andpost
have not been implemented yet in the REPL server.
1.2.7. Response
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\'")
;
A response encodes what is send back from the server to the browser client.
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
-
Response response(str content)
-
Response response(Status status, str explanation)
Utility to quickly render a string as HTML content
1.2.9. plain
Response plain(str text)
Utility to quickly make a plaintext response.
1.2.10. response
-
Response response(loc f)
-
default Response response(value val, map[str,str] header = ())
Utility to serve a file from any source location.
1.2.11. Status
data Status
= ok()
| created()
| accepted()
| noContent()
| partialContent()
| redirect()
| notModified()
| badRequest()
| unauthorized()
| forbidden()
| notFound()
| rangeNotSatisfiable()
| internalError()
;
Encoding of HTTP status
1.3. DateTime
import DateTime;
Library functions for date and time.
For operators on datetime
see DateTime in the Rascal Language Reference.
The following functions are defined for datetime:
-
now: Get the current datetime.
-
createDate: Create a new date.
-
createTime: Create a new time (with optional timezone offset).
-
createDateTime: Create a new datetime (with optional timezone offset).
-
joinDateAndTime: Create a new datetime by combining a date and a time.
-
splitDateTime: Split an existing datetime into a tuple with the date and the time.
-
incrementYears: Increment the years by given amount or by 1.
-
incrementMonths: Increment the months by a given amount or by 1.
-
incrementDays: Increment the days by given amount or by 1.
-
incrementHours: Increment the hours by a given amount or by 1.`
-
incrementMinutes: Increment the minutes by a given amount or by 1.
-
incrementSeconds: Increment the seconds by a given amount or by 1.
-
incrementMilliseconds: Increment the milliseconds by a given amount or by 1.
-
decrementYears: Decrement the years by a given amount or by 1.
-
decrementMonths: Decrement the months by a given amount or by 1.
-
decrementDays: Decrement the days by a given amount or by 1.
-
decrementHours: Decrement the hours by a given amount or by 1.
-
decrementMinutes: Decrement the minutes by a given amount or by 1.
-
decrementSeconds: Decrement the seconds by a given amount or by 1.
-
decrementMilliseconds: Decrement the milliseconds by a given amount or by 1.
-
interval: A closed interval on the time axis
-
createInterval: Given two datetime values, create an interval.
-
Duration: A duration of time, measured in individual years, months, etc
-
createDuration: Create a new duration representing the duration between the begin and end dates.
-
daysInInterval: Return the number of days in an interval, including the begin and end days.
-
daysDiff: Return the difference between two dates and/or datetimes in days.
-
dateRangeByDay: Given an interval, return a list of days.
-
parseDate: Parse an input date given as a string using the given format string.
-
parseDateInLocale: Parse an input date given as a string using a specific locale and format string
-
parseTime: Parse an input time given as a string using the given format string.
-
parseTimeInLocale: Parse an input time given as a string using a specific locale and format string
-
parseDateTime: Parse an input datetime given as a string using the given format string.
-
parseDateTimeInLocale: Parse an input datetime given as a string using a specific locale and format string
-
printDate: Print an input date using the given format string.
-
printDateInLocale: Print an input date using a specific locale and format string.
-
printTime: Print an input time using the given format string.
-
printTimeInLocale: Print an input time using a specific locale and format string
-
printDateTime: Print an input datetime using the given format string.
-
printDateTimeInLocale: Print an input datetime using a specific locale and format string
-
arbDateTime: Create a new arbitrary datetime.
1.3.1. now
datetime now()
Get the current datetime.
rascal>import DateTime;
ok
rascal>now();
datetime: $2021-02-17T16:04:30.017+00:00$
1.3.2. createDate
datetime createDate(int year, int month, int day)
Create a new date.
rascal>import DateTime;
ok
rascal>createDate(2012,1,1);
datetime: $2012-01-01$
1.3.3. createTime
-
datetime createTime(int hour, int minute, int second, int millisecond)
-
datetime createTime(int hour, int minute, int second, int millisecond, int timezoneHourOffset, int timezoneMinuteOffset)
Create a new time (with optional timezone offset).
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
-
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)
Create a new datetime (with optional timezone offset).
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
datetime joinDateAndTime(datetime date, datetime time)
Create a new datetime by combining a date and a time.
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
tuple[datetime date, datetime time] splitDateTime(datetime dt)
Split an existing datetime into a tuple with the date and the time.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.236+00:00$
rascal>splitDateTime(N);
tuple[datetime date,datetime time]: <$2021-02-17$,$T16:04:30.236+00:00$>
1.3.7. incrementYears
-
datetime incrementYears(datetime dt, int n)
-
datetime incrementYears(datetime dt)
Increment the years by given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.270+00:00$
rascal>incrementYears(N);
datetime: $2022-02-17T16:04:30.270+00:00$
rascal>incrementYears(N, 5);
datetime: $2026-02-17T16:04:30.270+00:00$
1.3.8. incrementMonths
-
datetime incrementMonths(datetime dt, int n)
-
datetime incrementMonths(datetime dt)
Increment the months by a given amount or by 1. .Function
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.306+00:00$
rascal>incrementMonths(N);
datetime: $2021-03-17T16:04:30.306+00:00$
rascal>incrementMonths(N, 5);
datetime: $2021-07-17T16:04:30.306+00:00$
1.3.9. incrementDays
-
datetime incrementDays(datetime dt, int n)
-
datetime incrementDays(datetime dt)
Increment the days by given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.342+00:00$
rascal>incrementDays(N);
datetime: $2021-02-18T16:04:30.342+00:00$
rascal>incrementDays(N, 5);
datetime: $2021-02-22T16:04:30.342+00:00$
1.3.10. incrementHours
-
datetime incrementHours(datetime dt, int n)
-
datetime incrementHours(datetime dt)
Increment the hours by a given amount or by 1.`
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.376+00:00$
rascal>incrementHours(N);
datetime: $2021-02-17T17:04:30.376+00:00$
rascal>incrementHours(N, 5);
datetime: $2021-02-17T21:04:30.376+00:00$
1.3.11. incrementMinutes
-
datetime incrementMinutes(datetime dt, int n)
-
datetime incrementMinutes(datetime dt)
Increment the minutes by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.411+00:00$
rascal>incrementMinutes(N);
datetime: $2021-02-17T16:05:30.411+00:00$
rascal>incrementMinutes(N, 5);
datetime: $2021-02-17T16:09:30.411+00:00$
1.3.12. incrementSeconds
-
datetime incrementSeconds(datetime dt, int n)
-
datetime incrementSeconds(datetime dt)
Increment the seconds by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.445+00:00$
rascal>incrementSeconds(N);
datetime: $2021-02-17T16:04:31.445+00:00$
rascal>incrementSeconds(N, 5);
datetime: $2021-02-17T16:04:35.445+00:00$
1.3.13. incrementMilliseconds
-
datetime incrementMilliseconds(datetime dt, int n)
-
datetime incrementMilliseconds(datetime dt)
Increment the milliseconds by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.479+00:00$
rascal>incrementMilliseconds(N);
datetime: $2021-02-17T16:04:30.480+00:00$
rascal>incrementMilliseconds(N, 5);
datetime: $2021-02-17T16:04:30.484+00:00$
1.3.14. decrementYears
-
datetime decrementYears(datetime dt, int n)
-
datetime decrementYears(datetime dt)
Decrement the years by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.514+00:00$
rascal>decrementYears(N);
datetime: $2020-02-17T16:04:30.514+00:00$
rascal>decrementYears(N, 5);
datetime: $2016-02-17T16:04:30.514+00:00$
1.3.15. decrementMonths
-
datetime decrementMonths(datetime dt, int n)
-
datetime decrementMonths(datetime dt)
Decrement the months by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.552+00:00$
rascal>decrementMonths(N);
datetime: $2021-01-17T16:04:30.552+00:00$
rascal>decrementMonths(N, 5);
datetime: $2020-09-17T16:04:30.552+00:00$
1.3.16. decrementDays
-
datetime decrementDays(datetime dt, int n)
-
datetime decrementDays(datetime dt)
Decrement the days by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.586+00:00$
rascal>decrementDays(N);
datetime: $2021-02-16T16:04:30.586+00:00$
rascal>decrementDays(N, 3);
datetime: $2021-02-14T16:04:30.586+00:00$
1.3.17. decrementHours
-
datetime decrementHours(datetime dt, int n)
-
datetime decrementHours(datetime dt)
Decrement the hours by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.620+00:00$
rascal>decrementHours(N);
datetime: $2021-02-17T15:04:30.620+00:00$
rascal>decrementHours(N, 5);
datetime: $2021-02-17T11:04:30.620+00:00$
1.3.18. decrementMinutes
-
datetime decrementMinutes(datetime dt, int n)
-
datetime decrementMinutes(datetime dt)
Decrement the minutes by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.655+00:00$
rascal>decrementMinutes(N);
datetime: $2021-02-17T16:03:30.655+00:00$
rascal>decrementMinutes(N, 5);
datetime: $2021-02-17T15:59:30.655+00:00$
1.3.19. decrementSeconds
-
datetime decrementSeconds(datetime dt, int n)
-
datetime decrementSeconds(datetime dt)
Decrement the seconds by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.689+00:00$
rascal>decrementSeconds(N);
datetime: $2021-02-17T16:04:29.689+00:00$
rascal>decrementSeconds(N, 5);
datetime: $2021-02-17T16:04:25.689+00:00$
1.3.20. decrementMilliseconds
-
datetime decrementMilliseconds(datetime dt, int n)
-
datetime decrementMilliseconds(datetime dt)
Decrement the milliseconds by a given amount or by 1.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:30.725+00:00$
rascal>decrementMilliseconds(N);
datetime: $2021-02-17T16:04:30.724+00:00$
rascal>decrementMilliseconds(N, 5);
datetime: $2021-02-17T16:04:30.720+00:00$
1.3.21. interval
data interval
= Interval(datetime begin, datetime end)
;
A closed interval on the time axis.
1.3.22. createInterval
interval createInterval(datetime begin, datetime end)
Given two datetime values, create an interval.
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2021-02-17T16:04:30.759+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2021-02-19T16:04:30.759+00:00$
rascal>createInterval(B, E);
interval: Interval($2021-02-17T16:04:30.759+00:00$,$2021-02-19T16:04:30.759+00:00$)
1.3.23. Duration
data Duration
= duration(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds)
;
A duration of time, measured in individual years, months, etc.
1.3.24. createDurationInternal
tuple[int,int,int,int,int,int,int] createDurationInternal(datetime begin, datetime end)
1.3.25. createDuration
-
Duration createDuration(datetime begin, datetime end)
-
Duration createDuration(interval i)
Create a new duration representing the duration between the begin and end dates.
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2021-02-17T16:04:30.794+00:00$
rascal>E1 = incrementHours(B);
datetime: $2021-02-17T17:04:30.794+00:00$
rascal>createDuration(B, E1);
Duration: duration(0,0,0,1,0,0,0)
rascal>E2 = incrementMinutes(B);
datetime: $2021-02-17T16:05:30.794+00:00$
rascal>createDuration(B, E2);
Duration: duration(0,0,0,0,1,0,0)
1.3.26. daysInInterval
int daysInInterval(interval i)
Return the number of days in an interval, including the begin and end days.
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2021-02-17T16:04:30.830+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2021-02-19T16:04:30.830+00:00$
rascal>I = createInterval(B, E);
interval: Interval($2021-02-17T16:04:30.830+00:00$,$2021-02-19T16:04:30.830+00:00$)
rascal>daysInInterval(I);
int: 2
1.3.27. daysDiff
int daysDiff(datetime begin, datetime end)
Return the difference between two dates and/or datetimes in days.
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2021-02-17T16:04:30.865+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2021-02-19T16:04:30.865+00:00$
rascal>daysDiff(B, E);
int: 2
1.3.28. dateRangeByDay
list[datetime] dateRangeByDay(interval i)
Given an interval, return a list of days.
Given an interval i
, return a list of days [i.begin, …, i.end]
.
rascal>import DateTime;
ok
rascal>B = now();
datetime: $2021-02-17T16:04:30.900+00:00$
rascal>E = incrementDays(B, 2);
datetime: $2021-02-19T16:04:30.900+00:00$
rascal>I = createInterval(B, E);
interval: Interval($2021-02-17T16:04:30.900+00:00$,$2021-02-19T16:04:30.900+00:00$)
rascal>dateRangeByDay(I);
list[datetime]: [$2021-02-17$,$2021-02-18$,$2021-02-19$]
1.3.29. parseDate
datetime parseDate(str inputDate, str formatString)
Parse an input date given as a string using the given format string.
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
datetime parseDateInLocale(str inputDate, str formatString, str locale)
Parse an input date given as a string using a specific locale and format string.
1.3.31. parseTime
datetime parseTime(str inputTime, str formatString)
Parse an input time given as a string using the given format string.
rascal>import DateTime;
ok
rascal>parseTime("11/21/19", "HH/mm/ss");
datetime: $T11:21:19.000+01:00$
1.3.32. parseTimeInLocale
datetime parseTimeInLocale(str inputTime, str formatString, str locale)
Parse an input time given as a string using a specific locale and format string.
1.3.33. parseDateTime
datetime parseDateTime(str inputDateTime, str formatString)
Parse an input datetime given as a string using the given format string.
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
datetime parseDateTimeInLocale(str inputDateTime, str formatString, str locale)
Parse an input datetime given as a string using a specific locale and format string.
1.3.35. printDate
-
str printDate(datetime inputDate, str formatString)
-
str printDate(datetime inputDate)
Print an input date using the given format string.
rascal>import DateTime;
ok
rascal>printDate(now());
str: "2021-02-17"
rascal>printDate(now(), "YYYYMMdd");
str: "20210217"
1.3.36. printDateInLocale
-
str printDateInLocale(datetime inputDate, str formatString, str locale)
-
str printDateInLocale(datetime inputDate, str locale)
Print an input date using a specific locale and format string.
rascal>import DateTime;
ok
rascal>printDateInLocale(now(), "Europe/Netherlands");
str: "2021-02-17"
rascal>printDateInLocale(now(), "French");
str: "2021-02-17"
1.3.37. printTime
-
str printTime(datetime inputTime, str formatString)
-
str printTime(datetime inputTime)
Print an input time using the given format string.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:31.110+00:00$
rascal>printTime(N);
str: "16:04:31.110+0000"
rascal>printTime(N, "HH/mm/ss");
str: "16/04/31"
1.3.38. printTimeInLocale
-
str printTimeInLocale(datetime inputTime, str formatString, str locale)
-
str printTimeInLocale(datetime inputTime, str locale)
Print an input time using a specific locale and format string.
1.3.39. printDateTime
-
str printDateTime(datetime inputDateTime, str formatString)
-
str printDateTime(datetime inputDateTime)
Print an input datetime using the given format string.
rascal>import DateTime;
ok
rascal>N = now();
datetime: $2021-02-17T16:04:31.145+00:00$
rascal>printDateTime(N);
str: "2021-02-17 16:04:31.145+0000"
rascal>printDateTime(N, "yyyy-MM-dd\'T\'HH:mm:ss.SSSZZ");
str: "2021-02-17T16:04:31.145+0000"
rascal>printDateTime(N, "YYYY/MM/dd/HH/mm/ss");
str: "2021/02/17/16/04/31"
1.3.40. printDateTimeInLocale
-
str printDateTimeInLocale(datetime inputDateTime, str formatString, str locale)
-
str printDateTimeInLocale(datetime inputDateTime, str locale)
Print an input datetime using a specific locale and format string.
1.3.41. arbDateTime
datetime arbDateTime()
Create a new arbitrary datetime.
rascal>import DateTime;
ok
rascal>arbDateTime();
datetime: $1428-09-26T15:21:59.923+00:00$
1.4. Exception
import Exception;
Exceptions thrown by the Rascal run-time.
1.4.1. RuntimeException
data RuntimeException
= Ambiguity(loc location, str nonterminal, str sentence)
| ArithmeticException(str message)
| AssertionFailed()
| AssertionFailed(str label)
| CallFailed(list[value] arguments)
| DateTimeParsingError(str message)
| DateTimePrintingError(str message)
| EmptyList()
| EmptyMap()
| EmptySet()
| IndexOutOfBounds(int index)
| IllegalArgument()
| IllegalArgument(value v)
| IllegalArgument(value v, str message)
| ImplodeError(str message)
| InvalidURI(str uri)
| InvalidUseOfDate(str message)
| InvalidUseOfDateTime(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()
| NoParent(loc location)
| NoSuchAnnotation(str label)
| NoSuchElement(value v)
| NoSuchField(str name)
| NoSuchKey(value key)
| NotImplemented(str message)
| ParseError(loc location)
| PathNotFound(loc l)
| PathNotFound(set[loc] locs)
| PermissionDenied()
| PermissionDenied(str message)
| RegExpSyntaxError(str message)
| SchemeNotSupported(loc location)
| StackOverflow()
| Timeout()
| UnavailableInformation()
;
The Exception
datatype used in all Rascal exceptions.
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.
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
import IO;
Library functions for input/output.
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]
-
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.
-
println: Print a value to the output stream and add a newline.
-
printlnExp: Print a value followed by a newline and return it as result.
-
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.
-
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.
-
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.
1.5.1. registerLocations
void registerLocations(str scheme, str authority, map[loc logical, loc physical] m)
register a logical file scheme including the resolution method via a table.
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.
-
Logical source locations are supported by IDE features such as hyperlinks
-
Logical source locations are supported by all IO functions as well
-
repeated calls to registerLocations for the same
scheme
andauthority
will overwrite them
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
void unregisterLocations(str scheme, str authority)
undo the effect of [registerLocations]
For debugging or for memory management you may wish to remove a lookup table.
1.5.3. resolveLocation
loc resolveLocation(loc l)
1.5.4. appendToFile
void appendToFile(loc file, value V…) throws PathNotFound, IO
Append a value to a file.
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.
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.
-
The same encoding pitfalls as the readFile function.
1.5.5. appendToFileEnc
void appendToFileEnc(loc file, str charset, value V…) throws PathNotFound, IO
Append a value to a file.
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
set[str] charsets()
Returns all available character sets.
1.5.7. canEncode
set[str] canEncode(str charset)
Returns whether this charset can be used for encoding (use with writeFile)
1.5.8. bprintln
bool bprintln(value arg)
Print a value and return true.
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
.
rascal>import IO;
ok
rascal>bprintln("Hello World");
Hello World
bool: true
1.5.9. exists
bool exists(loc file)
Check whether a given location exists.
Check whether a certain location exists, i.e., whether an actual file is associated with it.
rascal>import IO;
ok
Does the library file IO.rsc
exist?
rascal>exists(|std:///IO.rsc|);
bool: true
1.5.10. find
loc find(str name, list[loc] path) throws PathNotFound
Find a named file in a list of locations.
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
bool isDirectory(loc file)
Check whether a given location is a directory.
Check whether the location file
is a directory.
1.5.12. iprint
void iprint(value arg, int lineLimit = 1000)
Print an indented representation of a value.
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.
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
void iprintToFile(loc file, value arg)
Print an indented representation of a value to the specified location.
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.
rascal>import IO;
ok
rascal>iprintToFile(|file:///tmp/fruits.txt|, ["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
ok
1.5.14. iprintExp
&T iprintExp(&T v)
Print an indented representation of a value and returns the value as result.
See iprintlnExp for a version that adds a newline.
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
&T iprintlnExp(&T v)
Print an indented representation of a value followed by a newline and returns the value as result.
See iprintExp for a version that does not add a newline.
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
void iprintln(value arg, int lineLimit = 1000)
Print a indented representation of a value and add a newline at the end.
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.
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
bool isFile(loc file)
Check whether a given location is actually a file (and not a directory).
Check whether location file
is actually a file.
1.5.18. lastModified
datetime lastModified(loc file)
Last modification date of a location.
Returns last modification time of the file at location file
.
rascal>import IO;
ok
Determine the last modification date of the Rascal standard library:
rascal>lastModified(|std:///IO.rsc|);
datetime: $2021-02-17T15:31:03.000+00:00$
1.5.19. touch
void touch(loc file)
Set the modification date of a file to now
or create the file if it did not exist yet
1.5.20. setLastModified
void setLastModified(loc file, datetime timestamp)
Set the modification date of a file to the timestamp
1.5.21. listEntries
list[str] listEntries(loc file)
List the entries in a directory.
List the entries in directory file
.
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","Prelude$Less.class","analysis","Prelude$ByteBufferBackedInputStream.class","Grammar.rsc"]
1.5.22. mkDirectory
void mkDirectory(loc file) throws PathNotFound, IO
Create a new directory.
Create a directory at location file
.
1.5.23. print
void print(value arg)
Print a value without subsequent newline.
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.
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
-
&T printExp(&T v)
-
&T printExp(str msg, &T v)
Print a value and return it as result.
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
-
void println(value arg)
-
void println()
Print a value to the output stream and add a newline.
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.
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
-
&T printlnExp(&T v)
-
&T printlnExp(str msg, &T v)
Print a value followed by a newline and return it as result.
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
void rprint(value arg)
Raw print of a value.
This function is only available for internal use in the Rascal development team.
1.5.28. rprintln
void rprintln(value arg)
Raw print of a value followed by newline.
This function is only available for internal use in the Rascal development team.
1.5.29. readFile
str readFile(loc file) throws PathNotFound, IO
Read the contents of a location and return it as string value.
Return the contents of a file location as a single string. Also see readFileLines.
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.
-
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
str readFileEnc(loc file, str charset) throws PathNotFound, IO
Read the contents of a location and return it as string value.
Return the contents (decoded using the Character set supplied) of a file location as a single string. Also see readFileLinesEnc.
1.5.31. uuencode
str uuencode(loc file) throws PathNotFound, IO
1.5.32. readFileBytes
list[int] readFileBytes(loc file) throws PathNotFound, IO
Read the contents of a file and return it as a list of bytes.
1.5.33. readFileLines
list[str] readFileLines(loc file) throws PathNotFound, IO
Read the contents of a file location and return it as a list of strings.
Return the contents of a file location as a list of lines. Also see readFile.
Look at readFile to understand how this function chooses the character set. If you know the character set used, please use readFileLinesEnc.
-
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
list[str] readFileLinesEnc(loc file, str charset) throws PathNotFound, IO
Read the contents of a file location and return it as a list of strings.
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
void remove(loc file) throws IO
1.5.36. writeFile
void writeFile(loc file, value V…) throws PathNotFound, IO
Write values to a file.
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
void writeFileBytes(loc file, list[int] bytes) throws PathNotFound, IO
Write a list of bytes to a file.
1.5.38. writeFileEnc
void writeFileEnc(loc file, str charset, value V…) throws PathNotFound, IO
Write values to a file.
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
str md5HashFile(loc file) throws PathNotFound, IO
Read the contents of a location and return its MD5 hash.
MD5 hash the contents of a file location.
1.5.40. createLink
str createLink(str title, str target)
1.5.41. toBase64
str toBase64(loc file) throws PathNotFound, IO
1.5.42. copyFile
bool copyFile(loc source, loc target)
1.5.43. copyDirectory
bool copyDirectory(loc source, loc target)
1.5.44. arbLoc
loc arbLoc()
1.6. List
import List;
Library functions for lists.
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.
-
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:
-
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.
-
last:
-
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.
-
max:
-
merge: Merge the elements of two sorted lists into one list.
-
min: Determine the smallest element in a list.
-
min:
-
mix: Mix the elements of two lists.
-
permutations: Compute all permutations of a list.
-
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).
-
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 the elements of a list.
-
sum:
-
tail: Get the tail element(s) from a list.
-
tail:
-
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.
-
unzip2: Make a pair (triple) of lists from a list of pairs (triples).
-
upTill: Returns the list 0,1..n-1.
-
zip2: Make a list of pairs from two (three) lists of the same length.
-
zip3:
1.6.1. concat
list[&T] concat(list[list[&T]] xxs)
Concatenate a list of lists.
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
list[&T] delete(list[&T] lst, int n)
Delete an element from a list.
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.
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
map[&T element, int occurs] distribution(list[&T] lst)
Get the distribution of the elements of the list. That is how often does each element occur in the list?
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
list[&T] drop(int n, list[&T] lst)
Drop elements from the head of a list.
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].
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
list[&T] dup(list[&T] lst)
Remove multiple occurrences of elements in a list. The first occurrence remains.
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
&T elementAt(list[&T] lst, int index)
1.6.7. getOneFrom
&T getOneFrom(list[&T] lst)
Pick a random element from a list.
Get an arbitrary element from a list. See takeOneFrom for a function that also removes the selected element.
rascal>import List;
ok
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "zebra"
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "snake"
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "snake"
1.6.8. getFirstFrom
-
&T getFirstFrom([&T f, *&T _])
-
&T getFirstFrom(list[&T] _ :[])
Pick first element from a list.
Get the first element from a list. As opposed to getOneFrom this function always returns the same (first) list element.
1.6.9. head
-
&T head([&T h, *&T _])
-
&T head(list[&T] _:[])
-
list[&T] head(list[&T] lst, int n) throws IndexOutOfBounds
Get the first element(s) from a list.
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|(4590,9,<194,38>,<194,47>): EmptyList()
at head(|std:///List.rsc|(4552,52,<194,0>,<194,52>))
at $shell$(|prompt:///|(0,9,<1,0>,<1,9>))
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|(4644,113,<197,0>,<198,71>): IndexOutOfBounds(4)
at *** somewhere ***(|std:///List.rsc|(4644,113,<197,0>,<198,71>))
at head(|prompt:///|(19,1,<1,19>,<1,20>))
ok
1.6.10. headTail
-
tuple[&T, list[&T]] headTail([&T h, *&T t])
-
tuple[&T, list[&T]] headTail(list[&T] _:[])
Split a list in a head and a tail.
This function is identical to pop.
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
list[int] index(list[&T] lst)
A list of legal index values of a list.
Returns a list of all legal index values for a given list lst
.
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]
This function is useful in for loops over lists.
1.6.12. indexOf
int indexOf(list[&T] lst, &T elt)
Index of first occurrence of an element in a list.
Return index of first occurrence of elt
in lst
, or -1
if elt
is not found. Also see lastIndexOf.
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
list[&T] insertAt(list[&T] lst, int n, &T elm) throws IndexOutOfBounds
Insert an element at a specific position in a list.
Returns a new list with the value of elm
inserted at index position n
of the old list.
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|(6103,588,<265,0>,<285,83>): IndexOutOfBounds(10)
at *** somewhere ***(|std:///List.rsc|(6103,588,<265,0>,<285,83>))
at insertAt(|prompt:///|(22,1,<1,22>,<1,23>))
ok
1.6.14. intercalate
str intercalate(str sep, list[value] l)
Join a list of values into a string separated by a separator.
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
list[&T] intersperse(&T sep, list[&T] xs)
Intersperses a list of values with a separator.
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
bool isEmpty(list[&T] lst)
Test whether a list is empty.
Returns true
when a list is empty and false
otherwise.
rascal>import List;
ok
rascal>isEmpty([]);
bool: true
rascal>isEmpty([1, 2, 3]);
bool: false
1.6.17. last
-
&T last([*&T _, &T l])
-
&T last(list[&T] _:[])
Return the last element of a list, if any.
Also see tail that returns a list of one or more of the last elements of a list.
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
int lastIndexOf(list[&T] lst, &T elt)
Return index of last occurrence of elt in lst, or -1 if elt is not found.
Also see indexOf.
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
list[&U] mapper(list[&T] lst, &U (&T) fn)
Apply a function to all list elements and return list of results.
Apply a function fn
to each element of lst
and return the list of results.
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
-
&T max([&T h, *&T t])
-
&T max(list[&T] _:[])
Determine the largest element in a list.
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
-
list[&T] merge(list[&T] left, list[&T] right)
-
list[&T] merge(list[&T] left, list[&T] right, bool (&T a, &T b) lessOrEqual)
Merge the elements of two sorted lists into one list.
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.
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
-
&T min([&T h, *&T t])
-
&T min(list[&T] _: [])
Determine the smallest element in a list.
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
list[&T] mix(list[&T] l, list[&T] r)
Mix the elements of two lists.
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.
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
set[list[&T]] permutations(list[&T] lst)
Compute all permutations of a list.
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
set[list[&T]] permutationsBag(map[&T element, int occurs] b)
1.6.26. pop
tuple[&T, list[&T]] pop(list[&T] lst)
Pop top element from list, return a tuple. .Description This function is identical to headTail. Also see push and top.
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
list[&T] prefix(list[&T] lst)
Return all but the last element of a list.
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
list[&T] push(&T elem, list[&T] lst)
Push an element in front of a list.
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
&T reducer(list[&T] lst, &T (&T, &T) fn, &T unit)
Apply a function to successive elements of list and combine the results (deprecated).
Apply the function fn
to successive elements of list lst
starting with unit
.
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
WARNING: This function is deprecated, use a reducer instead.
1.6.30. remove
list[&T] remove(list[&T] lst, int indexToDelete)
1.6.31. removeFromBag
-
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
list[&T] reverse(list[&T] lst)
Reverse a list.
Returns a list with the elements of lst
in reverse order.
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
int size(list[&T] lst)
Determine the number of elements in a list.
rascal>import List;
ok
rascal>size([20, 10, 30]);
int: 3
rascal>size(["zebra", "elephant", "snake", "owl"]);
int: 4
1.6.34. slice
list[&T] slice(list[&T] lst, int begin, int len)
Compute a sublist of a list.
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. |
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
-
list[&T] sort(list[&T] lst)
-
list[&T] sort(list[&T] l, bool (&T a, &T b) less)
Sort the elements of a list.
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.
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","kiwi","pear"]
1.6.36. shuffle
-
list[&T] shuffle(list[&T] l)
-
list[&T] shuffle(list[&T] l, int seed)
Shuffle a list.
Returns a random (unbiased) shuffled list.
rascal>import List;
ok
rascal>shuffle([1,4,2,3]);
list[int]: [3,2,1,4]
rascal>shuffle(["zebra", "elephant", "snake", "owl"]);
list[str]: ["snake","zebra","owl","elephant"]
1.6.37. split
tuple[list[&T],list[&T]] split(list[&T] l)
Split a list into two halves.
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
-
(&T <:num) sum([(&T <: num) hd, *(&T <: num) tl])
-
(&T <:num) sum(list[&T] _: [])
Sum the elements of a list.
rascal>import List;
ok
rascal>sum([3, 1, 4, 5]);
int: 13
rascal>sum([3, 1.5, 4, 5]);
num: 13.5
1.6.39. tail
-
list[&T] tail([&T _, *&T t])
-
list[&T] tail(list[&T] _:[])
-
list[&T] tail(list[&T] lst, int len) throws IndexOutOfBounds
Get the tail element(s) from a list.
-
Return a list consisting of all but the first element of
lst
. -
Return a list consisting of the last
n
elements oflst
.
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|(17930,9,<785,44>,<785,53>): EmptyList()
at tail(|std:///List.rsc|(17886,58,<785,0>,<785,58>))
at $shell$(|prompt:///|(0,9,<1,0>,<1,9>))
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|(17947,115,<787,0>,<788,73>): IndexOutOfBounds(4)
at *** somewhere ***(|std:///List.rsc|(17947,115,<787,0>,<788,73>))
at tail(|prompt:///|(31,2,<1,31>,<1,33>))
ok
1.6.40. take
list[&T] take(int n, list[&T] lst)
Get number of elements from the head of a list.
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.
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
tuple[&T, list[&T]] takeOneFrom(list[&T] lst)
Remove an arbitrary element from a list, returns the element and the modified list.
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.
rascal>import List;
ok
rascal>takeOneFrom([10,20,30,40,50]);
tuple[int,list[int]]: <30,[10,20,40,50]>
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]]: <"owl",["zebra","elephant","snake"]>
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
list[&T] takeWhile(list[&T] lst, bool (&T a) take)
Take elements from the front of the list as long as a predicate is true.
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
map[&A,list[&B]] toMap(list[tuple[&A, &B]] lst) throws MultipleKey
Convert a list of pairs to a map; first elements are associated with a set of second elements.
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.
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]
)
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
map[&A,&B] toMapUnique(list[tuple[&A, &B]] lst) throws MultipleKey
Convert a list of tuples to a map; result must be a map.
Convert a list of tuples to a map; result must be a map.
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|(20463,667,<877,0>,<900,79>): MultipleKey(1,10,11)
at *** somewhere ***(|std:///List.rsc|(20463,667,<877,0>,<900,79>))
at toMapUnique(|prompt:///|(43,2,<1,43>,<1,45>))
ok
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
&T top([&T t, *&T _])
Take the top element of a list. .Description This function is identical to [head]. Also see pop and push.
rascal>import List;
ok
rascal>top([3, 1, 4, 5]);
int: 3
rascal>top(["zebra", "elephant", "snake", "owl"]);
str: "zebra"
1.6.46. toRel
rel[&T,&T] toRel(list[&T] lst)
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.
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
set[&T] toSet(list[&T] lst)
Convert a list to a set.
Convert lst
to a set.
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
str toString(list[&T] lst)
Convert a list to a string.
Convert lst
to a string.
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
str itoString(list[&T] lst)
Convert a list to an indented string.
Convert lst
to a indented string.
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. unzip2
tuple[list[&T],list[&U]] unzip2(list[tuple[&T,&U]] lst)
Make a pair (triple) of lists from a list of pairs (triples).
Also see [List-unzip];
rascal>import List;
ok
rascal>unzip2([<3,"thirty">, <1,"ten">, <4,"forty">]);
tuple[list[int],list[str]]: <[3,1,4],["thirty","ten","forty"]>
rascal>unzip3([<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. unzip3
tuple[list[&T],list[&U],list[&V]] unzip3(list[tuple[&T,&U,&V]] lst)
1.6.52. upTill
list[int] upTill(int n)
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.
rascal>import List;
ok
rascal>upTill(10);
list[int]: [0,1,2,3,4,5,6,7,8,9]
1.6.53. zip2
list[tuple[&T first, &U second]] zip2(list[&T] a, list[&U] b)
Make a list of pairs from two (three) lists of the same length.
Also see [List-unzip].
rascal>import List;
ok
rascal>zip3([3, 1, 4], ["thirty", "ten", "forty"]);
|prompt:///|(34,7,<1,34>,<1,41>): CallFailed([
[3,1,4],
["thirty","ten","forty"]
])
at $shell$(|prompt:///|(0,44,<1,0>,<1,44>))
ok
rascal>zip3([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>
]
WARNING: unexpected errors in the above SHELL example. Documentation author please fix!
1.6.54. zip3
list[tuple[&T first, &U second, &V third]] zip3(list[&T] a, list[&U] b, list[&V] c)
1.7. ListRelation
import ListRelation;
Library functions for list relations.
For operators on listrelations see ListRelation in the Rascal Language Reference.
The following functions are defined for list relations :
-
carrier: Return the list of all elements in any tuple in a list relation.
-
carrierR: A list relation restricted to certain element values in tuples.
-
carrierX: A list relation excluding tuples containing certain values.
-
complement: Complement of a list relation.
-
domain: Domain of a list relation: a list consisting of the first element of each tuple, uniquely.
-
domainR: List relation restricted to certain domain elements.
-
domainX: List relation excluding certain domain values.
-
groupDomainByRange: Make sets of elements in the domain that relate to the same element in the range.
-
groupRangeByDomain: Make sets of elements in the range that relate to the same element in the domain.
-
ident: The identity list relation.
-
invert: Invert the tuples in a list relation.
-
range: The range is composed of all but the first element of each tuple of a list relation, uniquely.
-
rangeR: List relation restricted to certain range values.
-
rangeX: List relation excluding certain range values.
-
index: Listes a binary list relation as a map
1.7.1. carrier
-
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)
Return the list of all elements in any tuple in a list relation.
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
-
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)
A list relation restricted to certain element values in tuples.
Returns list relation R
restricted to tuples with elements in set S
.
rascal>import ListRelation;
ok
rascal>carrierR([<1,10>, <2,20>, <3,30>], {10, 1, 20});
lrel[int,int]: [<1,10>]
1.7.3. carrierX
-
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)
A list relation excluding tuples containing certain values.
Returns list relation R
excluding tuples with some element in S
.
rascal>import ListRelation;
ok
rascal>carrierX([<1,10>, <2,20>, <3,30>], {10, 1, 20});
lrel[int,int]: [<3,30>]
1.7.4. complement
-
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)
Complement of a list relation.
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
.
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
-
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)
Domain of a list relation: a list consisting of the first element of each tuple, uniquely.
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.
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
-
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)
List relation restricted to certain domain elements.
Restriction of a list relation R
to tuples with first element in S
.
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
-
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)
List relation excluding certain domain values.
List relation R
excluding tuples with first element in S
.
rascal>import ListRelation;
ok
rascal>domainX([<1,10>, <2,20>, <3,30>], {3, 1});
lrel[int,int]: [<2,20>]
1.7.8. groupDomainByRange
list[list[&U]] groupDomainByRange(lrel[&U dom, &T ran] input)
Make sets of elements in the domain that relate to the same element in the range.
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
list[list[&T]] groupRangeByDomain(lrel[&U dom, &T ran] input)
Make sets of elements in the range that relate to the same element in the domain.
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
lrel[&T, &T] ident (list[&T] S)
The identity list relation.
The identity list relation for set S
.
rascal>import ListRelation;
ok
rascal>ident(["mon", "tue", "wed"]);
lrel[str,str]: [
<"mon","mon">,
<"tue","tue">,
<"wed","wed">
]
1.7.11. invert
-
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)
Invert the tuples in a list relation.
rascal>import ListRelation;
ok
rascal>invert([<1,10>, <2,20>]);
lrel[int,int]: [
<10,1>,
<20,2>
]
1.7.12. range
-
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)
The range is composed of all but the first element of each tuple of a list relation, uniquely.
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.
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
-
lrel[&T0,&T1] rangeR (lrel[&T0,&T1] R, set[&T1] S)
-
lrel[&T0,&T1] rangeR (lrel[&T0,&T1] R, list[&T1] L)
List relation restricted to certain range values.
Restriction of binary list relation R
to tuples with second element in set S
.
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
-
lrel[&T0,&T1] rangeX (lrel[&T0,&T1] R, set[&T1] S)
-
lrel[&T0,&T1] rangeX (lrel[&T0,&T1] R, list[&T1] S)
List relation excluding certain range values.
Restriction of binary list relation R
to tuples with second element not in set S
.
rascal>import ListRelation;
ok
rascal>rangeX([<1,10>, <2,20>, <3,30>], {30, 10});
lrel[int,int]: [<2,20>]
1.7.15. index
map[&K, set[&V]] index(lrel[&K, &V] R)
Listes a binary list relation as a map
Converts a binary list relation to a map of the domain to a set of the range.
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
list[&T] squeeze(list[&T] xs)
1.8. Location
import Location;
Library functions for source locations.
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
bool isSameFile(loc l, loc r)
Check that two locations refer to the same file.
1.8.2. isLexicallyLess
bool isLexicallyLess(loc l, loc r)
Compare two location values lexicographically.
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.
This ordering regards the location value itself as opposed to the text it refers to.
1.8.3. getContent
str getContent(loc l)
Get the textual content a location refers to.
1.8.4. isStrictlyContainedIn
bool isStrictlyContainedIn(loc inner, loc outer)
Is a location textually (strictly) contained in another location?
Strict containment between two locations inner
and outer
holds when
-
outer
's text begins beforeinner
's text, or -
outer
's text ends afterinner
's text, or -
both.
1.8.5. isContainedIn
bool isContainedIn(loc inner, loc outer)
Is a location textually contained in another location?
Containment between two locations inner
and outer
holds when
-
inner
andouter
are equal, or -
inner
is strictly contained inouter
.
1.8.6. beginsBefore
bool beginsBefore(loc l, loc r)
Begins a location’s text before (but may overlap with) another location’s text?
1.8.7. isBefore
bool isBefore(loc l, loc r)
Begins and ends a location’s text before another location’s text?
isBefore(l, r)
holds when l
's text occurs textually before r
's text.
1.8.8. isImmediatelyBefore
bool isImmediatelyBefore(loc l, loc r)
Occurs a location’s text immediately before another location’s text?
isImmediatelyBefore(l, r)
holds when l
's text occurs textually before, and is adjacent to, r
's text.
1.8.9. beginsAfter
bool beginsAfter(loc l, loc r)
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
bool isAfter(loc l, loc r)
Is a location’s text completely after another location’s text?
1.8.11. isImmediatelyAfter
bool isImmediatelyAfter(loc l, loc r)
Is a location’s text immediately after another location’s text?
1.8.12. isOverlapping
bool isOverlapping(loc l, loc r)
Refer two locations to text that overlaps?
1.8.13. cover
loc cover(list[loc] locs)
Compute a location that textually covers the text of a list of locations.
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
import Map;
Library functions for maps.
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.
-
toString: Convert a map to a string.
-
itoString: Convert a map to a indented string.
1.9.1. delete
map[&K,&V] delete(map[&K,&V] m, &K k)
Delete a key from a map.
Returns the map m
minus the key k
.
rascal>import Map;
ok
rascal>delete(("apple":1,"pear":2), "apple");
map[str, int]: ("pear":2)
1.9.2. domain
set[&K] domain(map[&K, &V] M)
Determine the domain (set of keys) of a map.
Returns the domain (set of keys) of map M
.
rascal>import Map;
ok
rascal>domain"apple": 1, "pear": 2;
set[str]: {"pear","apple"}
1.9.3. domainR
map[&K, &V] domainR(map[&K, &V] M, set[&K] S)
Map restricted to certain keys.
Return the map M
restricted to pairs with key in S
.
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
map[&K, &V] domainX(map[&K, &V] M, set[&K] S)
Map with certain keys excluded.
Return the map M
restricted to pairs with key not in S
.
rascal>import Map;
ok
rascal>domainX(("apple": 1, "pear": 2, "orange": 3), {"apple", "pear"});
map[str, int]: ("orange":3)
1.9.5. getOneFrom
&K getOneFrom(map[&K, &V] M)
Get a n arbitrary key from a map.
Returns an arbitrary key of map M
.
rascal>import Map;
ok
rascal>getOneFrom"apple": 1, "pear": 2, "pineapple": 3;
str: "pineapple"
rascal>getOneFrom"apple": 1, "pear": 2, "pineapple": 3;
str: "pear"
rascal>getOneFrom"apple": 1, "pear": 2, "pineapple": 3;
str: "pineapple"
1.9.6. invert
map[&V, set[&K]] invert(map[&K, &V] M)
Invert the (key,value) pairs in a map.
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.
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
map[&V, &K] invertUnique(map[&K, &V] M)
Invert the (key,value) pairs in a map.
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.
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|(2831,742,<131,0>,<157,54>): MultipleKey(1,"apple","orange")
at *** somewhere ***(|std:///Map.rsc|(2831,742,<131,0>,<157,54>))
at invertUnique(|prompt:///|(47,1,<1,47>,<1,48>))
ok
1.9.8. isEmpty
bool isEmpty(map[&K, &V] M)
Test whether a map is empty.
Returns true
if map M
is empty, and false
otherwise.
rascal>import Map;
ok
rascal>isEmpty)); bool: true rascal>isEmpty(("apple": 1, "pear": 2, "orange": 3;
bool: false
1.9.9. mapper
map[&K, &V] mapper(map[&K, &V] M, &L (&K) F, &W (&V) G)
Apply a function to all (key, value) pairs in a map.
Apply the functions F
and G
to each key/value pair in a map and return the transformed map.
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
set[&V] range(map[&K, &V] M)
The range (set of values that correspond to its keys) of a map.
Returns the range (set of values) of map M
.
rascal>import Map;
ok
rascal>range"apple": 1, "pear": 2;
set[int]: {1,2}
1.9.11. rangeR
map[&K, &V] rangeR(map[&K, &V] M, set[&V] S)
Map restricted to certain values in (key,values) pairs.
Returns the map restricted to pairs with values in S
.
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
map[&K, &V] rangeX(map[&K, &V] M, set[&V] S)
Map with certain values in (key,value) pairs excluded.
Returns the map restricted to pairs with values not in S
.
rascal>import Map;
ok
rascal>rangeX(("apple": 1, "pear": 2, "orange": 3), {2, 3});
map[str, int]: ("apple":1)
1.9.13. size
int size(map[&K, &V] M)
Number of (key, value) pairs in a map.
Returns the number of pairs in map M
.
rascal>import Map;
ok
rascal>size"apple": 1, "pear": 2, "orange": 3;
int: 3
1.9.14. toList
list[tuple[&K, &V]] toList(map[&K, &V] M)
Convert a map to a list of tuples.
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
-
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)
Convert a map to a relation.
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
str toString(map[&K, &V] M)
Convert a map to a string.
rascal>import Map;
ok
rascal>toString"apple": 1, "pear": 2, "orange": 3;
str: "(\"pear\":2,\"orange\":3,\"apple\":1)"
1.9.17. itoString
str itoString(map[&K, &V] M)
Convert a map to a indented string.
rascal>import Map;
ok
rascal>itoString"apple": 1, "pear": 2, "orange": 3;
str: "(\"pear\":2,\"orange\":3,\"apple\":1)"
1.10. Message
import Message;
A Message
datatype that represents messages in the IDE.
data Message = error(str msg, loc at)
| warning(str msg, loc at)
| info(str msg, loc at);
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
data Message
= error(str msg, loc at)
| error(str msg)
| warning(str msg, loc at)
| info(str msg, loc at)
;
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
import Node;
Library functions for nodes.
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.
-
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.
-
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
-
toString: Convert a node to a string.
-
itoString: Convert a node to an indented string.
1.11.1. arity
int arity(node T)
Determine the number of children of a node.
rascal>import Node;
ok
rascal>arity("f"(10, "abc"));
int: 2
rascal>arity("f"(10, "abc", false));
int: 3
1.11.2. getChildren
list[value] getChildren(node T)
Get the children of a node.
rascal>import Node;
ok
rascal>getChildren("f"(10, "abc"));
list[value]: [10,"abc"]
1.11.3. getKeywordParameters
map[str,value] getKeywordParameters(node T)
Get the keyword parameters of a node.
rascal>import Node;
ok
rascal>getKeywordParameters("f"(10, "abc", height=0));
map[str, value]: ("height":0)
1.11.4. getAnnotations
map[str, value] getAnnotations(node T)
1.11.5. setKeywordParameters
&T <: node setKeywordParameters(&T <: node x, map[str,value] keywordParameters)
Set the keyword parameters of a node.
rascal>import Node;
ok
rascal>setKeywordParameters("f"(10, "abc"), ("height":0));
node: "f"(10,"abc",
height=0)
1.11.6. setAnnotations
&T <: node setAnnotations(&T <: node x, map[str,value] keywordParameters)
1.11.7. getName
str getName(node T)
Determine the name of a node.
rascal>import Node;
ok
rascal>getName("f"(10, "abc"));
str: "f"
1.11.8. makeNode
node makeNode(str N, value V…, map[str, value] keywordParameters = ())
Create a node given its function name and arguments.
rascal>import Node;
ok
rascal>makeNode("f", [10, "abc"]);
node: "f"(10,"abc")
1.11.9. unset
&T <: node unset(&T <: node x, str keywordParameter)
Reset a specific keyword parameter back to their default on a node.
1.11.10. delAnnotation
&T <: node delAnnotation(&T <: node x, str keywordParameter)
1.11.11. unset
-
&T <: node unset(&T <: node x, set[str] keywordParameters)
-
&T <: node unset(&T <: node x)
Reset a set of keyword parameters back to their default on a node.
1.11.12. delAnnotations
&T <: node delAnnotations(&T <: node x)
1.11.13. unsetRec
&T unsetRec(&T x)
Recursively reset all keyword parameters of the node and its children back to their default.
1.11.14. delAnnotationsRec
&T delAnnotationsRec(&T x)
1.11.15. unsetRec
-
&T unsetRec(&T x, str keywordParameter)
-
&T <: node unsetRec(&T <: node x, set[str] keywordParameters)
Recursively reset a specific keyword parameter of the node and its children back to its default.
1.11.16. arbNode
node arbNode()
1.11.17. toString
str toString(node T)
Convert a node to a string.
rascal>import Node;
ok
rascal>F = "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.18. itoString
str itoString(node T)
Convert a node to an indented string.
rascal>import Node;
ok
rascal>F = "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\")"
1.12. ParseTree
import ParseTree;
Library functions for parse trees.
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 aProduction
to a list of childrenTree
nodes.Production
is the abstract representation of a rule in a syntax definition, which consists of a definition of an alternative for aSymbol
by a list ofSymbols
. -
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 alternativeTree
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:
-
Directly on the
Tree
level, just like any other algebraic data type. -
Using concrete syntax expressions and concrete syntax patterns.
-
Using actions.
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.
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
.
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
data Tree
= appl(Production prod, list[Tree] args)
| cycle(Symbol symbol, int cycleLength)
| amb(set[Tree] alternatives)
| char(int character)
;
The Tree data type as produced by the parser.
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
data Production
= prod(Symbol def, list[Symbol] symbols, set[Attr] attributes)
| regular(Symbol def)
| error(Production prod, int dot)
| skipped()
;
Production in ParseTrees
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
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
data Attr
= \bracket()
| \assoc(Associativity \assoc)
;
Attributes in productions.
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
data Associativity
= \left()
| \right()
| \assoc()
| \non-assoc()
;
Associativity attribute.
Associativity defines the various kinds of associativity of a specific production.
1.12.6. CharRange
data CharRange
= range(int begin, int end)
;
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
list[CharRange]
1.12.8. Symbol
data Symbol
= \start(Symbol symbol)
;
Symbols that can occur in a ParseTree
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
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
data Symbol
= \lit(str string)
| \cilit(str string)
| \char-class(list[CharRange] ranges)
;
1.12.11. Symbol
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
data Symbol
= \conditional(Symbol symbol, set[Condition] conditions)
;
1.12.13. subtype
bool subtype(Symbol::\sort(_), Symbol::\adt("Tree", _))
1.12.14. Condition
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)
;
Datatype for declaring preconditions and postconditions on symbols
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
Production priority(Symbol s, [*Production a, priority(Symbol _, list[Production] b), *Production c])
Nested priority is flattened.
1.12.16. associativity
-
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)
Normalization of associativity.
-
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
-
&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)
Parse input text (from a string or a location) and return a parse tree.
-
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 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
.
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. parser
&T (value input, loc origin) parser(type[&T] grammar, bool allowAmbiguity=false, bool hasSideEffects=false, bool firstAmbiguity=false)
Generates a parser from an input grammar.
This builtin function wraps the Rascal parser generator by transforming a grammar into a parsing function.
The resulting parsing function has the following overloaded signature:
-
Tree parse(str input, loc origin);
-
Tree parse(loc input, loc origin);
So the parse function reads either directly from a str or via the contents of a loc. It also takes a origin
parameter which leads to the prefix of the src
fields of the resulting tree.
The parse function behaves differently depending of the given keyword parameters: * allowAmbiguity
: if true then no exception is thrown in case of ambiguity and a parse forest is returned. if false, * the parser throws an exception during tree building and produces only the first ambiguous subtree in its message. * if set to false
, the parse constructs trees in linear time. if set to true
the parser constructs trees in polynomial time. * * hasSideEffects
: if false then the parser is a lot faster when constructing trees, since it does not execute the parse actions in an * interpreted environment to make side effects (like a symbol table) and it can share more intermediate results as a result. * * firstAmbiguity
: if true, then the parser returns the subforest for the first (left-most innermost) ambiguity instead of a parse tree for * the entire input string. This is for grammar debugging purposes a much faster solution then waiting for an entire * parse forest to be constructed in polynomial time.
1.12.19. parsers
&U (type[&U] nonterminal, value input, loc origin) parsers(type[&T] grammar, bool allowAmbiguity=false, bool hasSideEffects=false, bool firstAmbiguity=false)
Generates parsers from a grammar (reified type), where all non-terminals in the grammar can be used as start-symbol.
This parser generator behaves the same as the parser
function, but it produces parser functions which have an additional nonterminal parameter. This can be used to select a specific non-terminal from the grammar to use as start-symbol for parsing.
1.12.20. firstAmbiguity
-
Tree firstAmbiguity(type[&T<:Tree] begin, str input)
-
Tree firstAmbiguity(type[&T<:Tree] begin, loc input)
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.21. unparse
str unparse(Tree tree)
Yield the string of characters that form the leafs of the given parse tree.
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
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.22. printSymbol
str printSymbol(Symbol sym, bool withLayout)
1.12.23. implode
&T<:value implode(type[&T<:value] t, Tree tree)
Implode a parse tree according to a given (ADT) type.
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 fields are propagated as keyword fields on constructor ASTs. To access them, the user is required to explicitly declare a keyword field on all ADTs used in implosion. In other words, for every ADT type T
, add:
data T(loc location=|unknown);
Here are some examples for the above rules.
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).
Given the grammar
syntax Formal = formal: "VAR"? {Id ","}+ ":" Type;
The corresponding ADT could be:
data Formal = formal(bool, list[str], Type);
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);
Given the grammar
syntax Exp = left add: Exp "+" Exp;
Can be imploded into:
data Exp = add(Exp, Exp);
1.12.24. TreeSearchResult
data TreeSearchResult[&T<:Tree]
= treeFound(&T tree)
| treeNotFound()
;
Tree search result type for treeAt.
1.12.25. treeAt
-
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)
Select the innermost Tree of a given type which is enclosed by a given location.
1.12.26. sameType
-
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.27. isNonTerminalType
-
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)
Determine if the given type is a non-terminal type.
1.13. Relation
import Relation;
Library functions for relations.
For operators on relations see Relation in the Rascal Language Reference.
The following functions are defined for relations:
-
carrier: Return the set of all elements in any tuple in a relation.
-
carrierR: A relation restricted to certain element values in tuples.
-
carrierX: A relation excluded tuples containing certain values.
-
complement: Complement of a relation.
-
domain: Domain of a relation: a set consisting of the first element of each tuple.
-
domainR: Relation restricted to certain domain elements.
-
domainX: Relation excluding certain domain values.
-
groupDomainByRange: Make sets of elements in the domain that relate to the same element in the range.
-
groupRangeByDomain: Make sets of elements in the range that relate to the same element in the domain.
-
ident: The identity relation.
-
invert: Invert the tuples in a relation.
-
range: The range (i.e., all but the first element of each tuple) of a relation.
-
rangeR: Relation restricted to certain range values.
-
rangeX: Relation excluding certain range values.
-
index: Indexes a binary relation as a map
1.13.1. carrier
-
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)
Return the set of all elements in any tuple in a relation.
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
-
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)
A relation restricted to certain element values in tuples.
Returns relation R
restricted to tuples with elements in set S
.
rascal>import Relation;
ok
rascal>carrierR({<1,10>, <2,20>, <3,30>}, {10, 1, 20});
rel[int,int]: {<1,10>}
1.13.3. carrierX
-
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)
A relation excluded tuples containing certain values.
Returns relation R
excluding tuples with some element in S
.
rascal>import Relation;
ok
rascal>carrierX({<1,10>, <2,20>, <3,30>}, {10, 1, 20});
rel[int,int]: {<3,30>}
1.13.4. complement
-
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)
Complement of a relation.
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
.
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
-
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)
Domain of a relation: a set consisting of the first element of each tuple.
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
-
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)
Relation restricted to certain domain elements.
Restriction of a relation R
to tuples with first element in S
.
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
-
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)
Relation excluding certain domain values.
Relation R
excluded tuples with first element in S
.
rascal>import Relation;
ok
rascal>domainX({<1,10>, <2,20>, <3,30>}, {3, 1});
rel[int,int]: {<2,20>}
1.13.8. groupDomainByRange
set[set[&U]] groupDomainByRange(rel[&U dom, &T ran] input)
Make sets of elements in the domain that relate to the same element in the range.
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
set[set[&T]] groupRangeByDomain(rel[&U dom, &T ran] input)
Make sets of elements in the range that relate to the same element in the domain.
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
rel[&T, &T] ident (set[&T] S)
The identity relation.
The identity relation for set S
.
rascal>import Relation;
ok
rascal>ident({"mon", "tue", "wed"});
rel[str,str]: {
<"tue","tue">,
<"mon","mon">,
<"wed","wed">
}
1.13.11. invert
-
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)
Invert the tuples in a relation.
rascal>import Relation;
ok
rascal>invert({<1,10>, <2,20>});
rel[int,int]: {
<10,1>,
<20,2>
}
1.13.12. range
-
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)
The range (i.e., all but the first element of each tuple) of a relation.
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
rel[&T0,&T1] rangeR (rel[&T0,&T1] R, set[&T2] S)
Relation restricted to certain range values.
Restriction of binary relation R
to tuples with second element in set S
.
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
rel[&T0,&T1] rangeX (rel[&T0,&T1] R, set[&T2] S)
Relation excluding certain range values.
Restriction of binary relation R
to tuples with second element not in set S
.
rascal>import Relation;
ok
rascal>rangeX({<1,10>, <2,20>, <3,30>}, {30, 10});
rel[int,int]: {<2,20>}
1.13.15. index
map[&K, set[&V]] index(rel[&K, &V] R)
Indexes a binary relation as a map
Converts a binary relation to a map of the domain to a set of the range.
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
import Set;
Library functions for sets.
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 theless
function -
top:
-
union: Flatten a set of sets into a single set
-
jaccard: Compute the Jaccard similarity between two sets
1.14.1. classify
map[&K,set[&V]] classify(set[&V] input, &K (&V) getClass)
Classify elements in a set.
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
set[set[&T]] group(set[&T] input, bool (&T a, &T b) similar)
Group elements in a set given an equivalence function.
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
map[&T,int] index(set[&T] s)
Map set elements to a fixed index.
rascal>import Set;
ok
rascal>index({"elephant", "zebra", "snake"});
map[str, int]: ("snake":0,"zebra":1,"elephant":2)
1.14.4. isEmpty
bool isEmpty(set[&T] st)
Test whether a set is empty.
Yields true
if s
is empty, and false
otherwise.
rascal>import Set;
ok
rascal>isEmpty({1, 2, 3});
bool: false
rascal>isEmpty({});
bool: true
1.14.5. mapper
set[&U] mapper(set[&T] st, &U (&T) fn)
Apply a function to all set elements and return set of results.
Return a set obtained by applying function fn
to all elements of set s
.
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
&T max(set[&T] st)
Determine the largest element of a set.
rascal>import Set;
ok
rascal>max({1, 3, 5, 2, 4});
int: 5
rascal>max({"elephant", "zebra", "snake"});
str: "zebra"
1.14.7. min
&T min(set[&T] st)
Determine the smallest element of a set.
rascal>import Set;
ok
rascal>min({1, 3, 5, 4, 2});
int: 1
1.14.8. power
set[set[&T]] power(set[&T] st)
Determine the powerset of a set.
Returns a set with all subsets of s
.
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
set[set[&T]] power1(set[&T] st)
The powerset (excluding the empty set) of a set value.
Returns all subsets (excluding the empty set) of s
.
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
-
&T reducer(set[&T] st, &T (&T,&T) fn, &T unit)
-
&T reducer(set[&T] _:{})
Apply a function to successive elements of a set and combine the results (deprecated).
Apply the function fn
to successive elements of set s
starting with unit
.
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
int size(set[&T] st)
Determine the number of elements in a set.
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
-
(&T <:num) sum(set[(&T <:num)] _:{})
-
default (&T <:num) sum({(&T <: num) e, *(&T <: num) r})
1.14.13. getOneFrom
&T getOneFrom(set[&T] st)
Pick an arbitrary element from a set.
rascal>import Set;
ok
rascal>getOneFrom({"elephant", "zebra", "snake"});
str: "zebra"
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
-
&T getFirstFrom({&T f, *&T _})
-
&T getFirstFrom(set[&T] _:{})
Get "first" element from a set.
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.
This function helps to make set-based code more deterministic, for instance, for testing purposes.
1.14.15. takeOneFrom
tuple[&T, set[&T]] takeOneFrom(set[&T] st)
Remove an arbitrary element from a set, returns the element and a set without that element.
Remove an arbitrary element from set s
and return a tuple consisting of the element and a set without that element. Also see getOneFrom.
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]]: <4,{1,3,2}>
rascal>takeOneFrom({1, 2, 3, 4});
tuple[int,set[int]]: <3,{1,2,4}>
1.14.16. takeFirstFrom
-
tuple[&T, set[&T]] takeFirstFrom({&T f, *&T r})
-
tuple[&T, set[&T]] takeFirstFrom(set[&T] _:{})
Remove "first" element from a set, returns the element and a set without that element.
element of a set.
1.14.17. toList
list[&T] toList(set[&T] st)
Convert a set to a list.
rascal>import Set;
ok
rascal>toList({1, 2, 3, 4});
list[int]: [1,3,2,4]
rascal>toList({"elephant", "zebra", "snake"});
list[str]: ["snake","zebra","elephant"]
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]
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
map[&A,set[&B]] toMap(rel[&A, &B] st)
Convert a set of tuples to a map; each key is associated with a set of values.
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.
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
map[&A,&B] toMapUnique(rel[&A, &B] st) throws MultipleKey
Convert a set of tuples to a map (provided that there are no multiple keys).
Convert a set of tuples to a map. The result should be a legal map (i.e., without multiple keys).
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|(9335,552,<418,0>,<437,70>): MultipleKey("a",10,1)
at *** somewhere ***(|std:///Set.rsc|(9335,552,<418,0>,<437,70>))
at toMapUnique(|prompt:///|(39,2,<1,39>,<1,41>))
ok
1.14.20. toString
str toString(set[&T] st)
Convert a set to a string.
rascal>import Set;
ok
rascal>toString({1, 2, 3});
str: "{1,3,2}"
rascal>toString({"elephant", "zebra", "snake"});
str: "{\"snake\",\"zebra\",\"elephant\"}"
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
str itoString(set[&T] st)
Convert a set to an indented string.
rascal>import Set;
ok
rascal>toString({1, 2, 3});
str: "{1,3,2}"
rascal>toString({"elephant", "zebra", "snake"});
str: "{\"snake\",\"zebra\",\"elephant\"}"
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
-
list[&T] sort(set[&T] s)
-
list[&T] sort(set[&T] l, bool (&T a, &T b) less)
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
andb < c
thena < c
.
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
-
list[&T] top(int k, set[&T] l, bool (&T a, &T b) less)
-
list[&T] top(int k, set[&T] l)
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
set[&T] union(set[set[&T]] sets)
Flatten a set of sets into a single set.
1.14.25. jaccard
real jaccard(set[value] x, set[value] y)
Compute the Jaccard similarity between two sets.
1.15. String
import String;
Library functions for strings.
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.
-
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.
-
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.
-
toInt: Convert a string value to integer.
-
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
-
wrap: Word wrap a string to fit in a certain width.
-
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
-
str center(str s, int n)
-
str center(str s, int n, str pad)
Center a string in given space.
-
Center string
s
in string of lengthn
using spaces. -
Center string
s
in string of lengthn
usingpad
as padding character.
rascal>import String;
ok
rascal>center("abc", 10);
str: " abc "
rascal>center("abc", 10, "x");
str: "xxxabcxxxx"
1.15.2. charAt
int charAt(str s, int i) throws IndexOutOfBounds
Return character in a string by its index position.
Return the character at position i
in string s
as integer character code. Also see stringChar that converts character codes back to string.
rascal>import String;
ok
rascal>charAt("abc", 0);
int: 97
rascal>stringChar(charAt("abc", 0));
str: "a"
1.15.3. chars
list[int] chars(str s)
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.
rascal>import String;
ok
rascal>chars("abc");
list[int]: [97,98,99]
rascal>stringChars(chars("abc")) == "abc";
bool: true
1.15.4. contains
bool contains(str input, str find)
Check that a string contains another string.
Check whether the string find
occurs as substring in the string subject
.
rascal>import String;
ok
rascal>contains("abracadabra", "bra");
bool: true
rascal>contains("abracadabra", "e");
bool: false
1.15.5. deescape
str deescape(str s)
Replace escaped characters by the escaped character itself (using Rascal escape conventions).
1.15.6. endsWith
bool endsWith(str subject, str suffix)
Check whether a string ends with a given substring.
Yields true
if string subject
ends with the string suffix
.
rascal>import String;
ok
rascal>endsWith("Hello.rsc", ".rsc");
bool: true
1.15.7. escape
str escape(str subject, map[str,str] mapping)
Replace single characters in a string.
Return a copy of subject
in which each single character key in replacements has been replaced by its associated value.
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
list[int] findAll(str subject, str find)
Find all occurrences of a string in another string.
Find all occurrences of string find
in string subject
. The result is a (possible empty) list of positions where find
matches.
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
int findFirst(str subject, str find)
Find the first occurrence of a string in another string.
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.
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
int findLast(str subject, str find)
Find the last occurrence of a string in another string.
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.
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
bool isEmpty(str s)
Check whether a string is empty.
Returns true
if string s
is empty.
rascal>import String;
ok
rascal>isEmpty("");
bool: true
rascal>isEmpty("abc");
bool: false
1.15.12. arbString
str arbString(int n)
Generate a arbitrary string.
Returns a string of maximum n
length, with arbitrary characters.
rascal>import String;
ok
rascal>arbString(3);
str: "\n\n\t"
rascal>arbString(10);
str: ""
1.15.13. left
-
str left(str s, int n)
-
str left(str s, int n, str pad)
Left alignment of string in given space.
-
Left align string
s
in string of lengthn
using spaces. -
Left align string
s
in string of lengthn
usingpad
as pad character.
rascal>import String;
ok
rascal>left("abc", 10);
str: "abc "
rascal>left("abc", 10, "x");
str: "abcxxxxxxx"
1.15.14. replaceAll
str replaceAll(str subject, str find, str replacement)
Replace all occurrences of a string in another string.
Return a copy of subject
in which all occurrences of find
(if any) have been replaced by replacement
. Also see replaceFirst and replaceLast.
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"
Note that find
is a string (as opposed to, for instance, a regular expression in Java).
1.15.15. replaceFirst
str replaceFirst(str subject, str find, str replacement)
Replace the first occurrence of a string in another string.
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.
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"
Note that find
is a string (as opposed to, for instance, a regular expression in Java).
1.15.16. replaceLast
str replaceLast(str subject, str find, str replacement)
Replace the last occurrence of a string in another string.
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.
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"
Note that find
is a string (as opposed to, for instance, a regular expression in Java).
1.15.17. reverse
str reverse(str s)
Return a string with all characters in reverse order.
Returns string with all characters of string s
in reverse order.
rascal>import String;
ok
rascal>reverse("abc");
str: "cba"
1.15.18. right
-
str right(str s, int n)
-
str right(str s, int n, str pad)
Right alignment of a string value in a given space.
-
Right align string
s
in string of lengthn
using spaces. -
Right align string
s
in string of lengthn
usingpad
as pad character.
rascal>import String;
ok
rascal>right("abc", 10);
str: " abc"
rascal>right("abc", 10, "x");
str: "xxxxxxxabc"
1.15.19. size
int size(str s)
Determine length of a string value.
Returns the length (number of characters) in string s
.
rascal>import String;
ok
rascal>size("abc");
int: 3
rascal>size("");
int: 0
1.15.20. startsWith
bool startsWith(str subject, str prefix)
Check whether a string starts with a given prefix.
Yields true
if string subject
starts with the string prefix
.
rascal>import String;
ok
rascal>startsWith("Hello.rsc", "Hell");
bool: true
1.15.21. stringChar
str stringChar(int char) throws IllegalArgument
Convert a character code into a string.
1.15.22. stringChars
str stringChars(list[int] chars) throws IllegalArgument
Convert a list of character codes into a string.
1.15.23. isValidCharacter
bool isValidCharacter(int ch)
Check that a given integer value is a valid Unicode code point.
1.15.24. substring
-
str substring(str s, int begin)
-
str substring(str s, int begin, int end)
Extract a substring from a string value.
-
Yields substring of string
s
from indexbegin
to the end of the string. -
Yields substring of string
s
from indexbegin
to (but not including) indexend
.
rascal>import String;
ok
rascal>substring("abcdef", 2);
str: "cdef"
rascal>substring("abcdef", 2, 4);
str: "cd"
1.15.25. toInt
-
int toInt(str s) throws IllegalArgument
-
int toInt(str s, int r) throws IllegalArgument
Convert a string value to integer.
-
Converts string
s
to integer. -
Convert string
s
to integer using radixr
.
Throws IllegalArgument
when s
cannot be converted.
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
str toLowerCase(str s)
Convert the characters in a string value to lower case.
Convert all characters in string s
to lowercase. Also see toUpperCase.
rascal>import String;
ok
rascal>toLowerCase("AaBbCc123");
str: "aabbcc123"
1.15.27. toReal
real toReal(str s)
Convert a string value to real.
Converts string s
to a real. Throws IllegalArgument
when s
cannot be converted.
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
str toUpperCase(str s)
Convert the characters in a string value to upper case.
Converts all characters in string s
to upper case.
Also see toLowerCase.
rascal>import String;
ok
rascal>toUpperCase("AaBbCc123");
str: "AABBCC123"
1.15.29. trim
str trim(str s)
Returns string with leading and trailing whitespace removed.
rascal>import String;
ok
rascal>trim(" jelly
>>>>>>>beans ");
str: "jelly\nbeans"
1.15.30. squeeze
str squeeze(str src, str charSet)
Squeeze repeated occurrences of characters. .Description Squeeze repeated occurrences in src
of characters in charSet
removed. See Apache
for the allowed syntax in charSet
.
rascal>import String;
ok
rascal>squeeze("hello", "el");
str: "helo"
1.15.31. split
list[str] split(str sep, str src)
Split a string into a list of strings based on a literal separator.
1.15.32. capitalize
str capitalize(str src)
1.15.33. uncapitalize
str uncapitalize(str src)
1.15.34. toBase64
str toBase64(str src)
1.15.35. fromBase64
str fromBase64(str src)
1.15.36. wrap
str wrap(str src, int wrapLength)
Word wrap a string to fit in a certain width.
Inserts newlines in a string in order to fit the string in a certain width. It only breaks on spaces (' ').
1.15.37. format
str format(str s, str dir, int n, str pad)
1.15.38. rexpMatch
bool rexpMatch(str s, str re)
Determine if a string matches the given (Java-syntax) regular expression.
1.15.39. toLocation
loc toLocation(str s)
Convert a string value to a (source code) location.
-
Converts string
s
to a location. -
If the scheme is not provided, it is assumed to be
cwd
.
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
str substitute(str src, map[loc,str] s)
Substitute substrings in a string based on a substitution map from location to string.
rascal>import String;
ok
rascal>substitute("abc", (|stdin:///|(1,1): "d"))
str: "adc"
1.16. Type
import Type;
Rascal’s type system, implemented in Rascal itself.
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.
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
data Symbol
= \int()
| \bool()
| \real()
| \rat()
| \str()
| \num()
| \node()
| \void()
| \value()
| \loc()
| \datetime()
;
A Symbol represents a Rascal Type.
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. |
1.16.2. Symbol
data Symbol
= \label(str name, Symbol symbol)
;
1.16.3. Symbol
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)
| \overloaded(set[Symbol] alternatives)
| \var-func(Symbol ret, list[Symbol] parameters, Symbol varArg)
| \reified(Symbol symbol)
;
1.16.4. Symbol
data Symbol
= \parameter(str name, Symbol bound)
;
1.16.5. Production
data Production
= \cons(Symbol def, list[Symbol] symbols, list[Symbol] kwTypes, set[Attr] attributes)
| \choice(Symbol def, set[Production] alternatives)
| \composition(Production lhs, Production rhs)
;
A production in a grammar or constructor in a data type.
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
data Attr
= \tag(value \tag)
;
Attributes register additional semantics annotations of a definition.
[[Type-\var-func]] ## \var-func
Symbol \var-func(Symbol ret, list[Symbol] parameters, Symbol varArg)
Transform a function with varargs (…
) to a normal function with a list argument.
1.16.7. choice
Production choice(Symbol s, set[Production] choices)
Normalize the choice between alternative productions.
Nested choice is flattened.
1.16.8. subtype
-
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] kw1), Symbol::\func(Symbol r2, list[Symbol] p2, list[Symbol] kw2))
-
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)
Subtype on types.
1.16.9. comparable
bool comparable(Symbol s, Symbol t)
Check if two types are comparable, i.e., have a common supertype.
1.16.10. equivalent
bool equivalent(Symbol s, Symbol t)
Check if two types are equivalent.
1.16.11. eq
bool eq(value x, value y)
Structural equality between values.
The difference is that no implicit coercions are done between values of incomparable types, such as == does for int, real and rat.
rascal>import Type;
ok
rascal>1 == 1.0
bool: true
rascal>eq(1,1.0)
bool: false
1.16.12. lub
-
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))
The least-upperbound (lub) between two types.
This function documents and implements the lub operation in Rascal’s type system.
1.16.13. keepParams
bool keepParams(Symbol::\parameter(str s1, Symbol bound1), Symbol::\parameter(str s2, Symbol bound2))
1.16.14. lub
-
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
bool allLabeled(list[Symbol] l)
1.16.16. noneLabeled
bool noneLabeled(list[Symbol] l)
1.16.17. getLabels
list[str] getLabels(list[Symbol] l)
1.16.18. addLabels
-
list[Symbol] addLabels(list[Symbol] l, list[str] s)
-
default list[Symbol] addLabels(list[Symbol] l, list[str] s)
1.16.19. stripLabels
list[Symbol] stripLabels(list[Symbol] l)
1.16.20. getParamLabels
list[str] getParamLabels(list[Symbol] l)
1.16.21. addParamLabels
-
list[Symbol] addParamLabels(list[Symbol] l, list[str] s)
-
default list[Symbol] addParamLabels(list[Symbol] l, list[str] s)
1.16.22. glb
-
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] kwl), Symbol::\func(Symbol rr, list[Symbol] rp, list[Symbol] kwr))
-
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)
The greatest lower bound (glb) between two types.
This function documents and implements the glb operation in Rascal’s type system.
1.16.23. Exception
data Exception
= typeCastException(Symbol from, type[value] to)
;
1.16.24. typeCast
&T typeCast(type[&T] typ, value v)
1.16.25. make
-
&T make(type[&T] typ, str name, list[value] args)
-
&T make(type[&T] typ, str name, list[value] args, map[str,value] keywordArgs)
Instantiate an ADT constructor of a given type with the given children and optional keyword arguments.
This function will build a constructor if the definition exists and throw an exception otherwise.
1.16.26. typeOf
Symbol typeOf(value v)
Returns the dynamic type of a value as a reified type.
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.
rascal>import Type;
ok
rascal>value x = 1;
value: 1
rascal>typeOf(x)
Symbol: int()
-
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
-
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 _)
Determine if the given type is an int.
1.16.28. isBoolType
-
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 _)
Determine if the given type is a bool.
1.16.29. isRealType
-
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 _)
Determine if the given type is a real.
1.16.30. isRatType
-
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 _)
Determine if the given type is a rational.
1.16.31. isStrType
-
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 _)
Determine if the given type is a string.
1.16.32. isNumType
-
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 _)
Determine if the given type is a num.
1.16.33. isNodeType
-
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 _)
Determine if the given type is a node.
1.16.34. isVoidType
-
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 _)
Determine if the given type is a void.
1.16.35. isValueType
-
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 _)
Determine if the given type is a value.
1.16.36. isLocType
-
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 _)
Determine if the given type is a loc.
1.16.37. isDateTimeType
-
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 _)
Determine if the given type is a datetime
.
1.16.38. isSetType
-
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 _)
Determine if the given type is a set.
1.16.39. isRelType
-
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 _)
Determine if the given type is a relation.
1.16.40. isListRelType
-
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 _)
Determine if the given type is a list relation.
1.16.41. isTupleType
-
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 _)
Determine if the given type is a tuple.
1.16.42. isListType
-
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 _)
Determine if the given type is a list.
1.16.43. isListRelType
-
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 _)
Determine if the given type is a list relation.
1.16.44. isMapType
-
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 _)
Determine if the given type is a map.
1.16.45. isBagType
-
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 _)
Determine if the given type is a bag (bags are not yet implemented).
1.16.46. isADTType
-
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 _)
Determine if the given type is an Abstract Data Type (ADT).
1.16.47. isConstructorType
-
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 _)
Determine if the given type is a constructor.
1.16.48. isAliasType
-
bool isAliasType(Symbol::\alias(,,_))
-
bool isAliasType(Symbol::\parameter(_,Symbol tvb))
-
bool isAliasType(Symbol::\label(_,Symbol lt))
-
default bool isAliasType(Symbol _)
Determine if the given type is an alias.
1.16.49. isFunctionType
-
bool isFunctionType(Symbol::\alias(,,Symbol at))
-
bool isFunctionType(Symbol::\parameter(_,Symbol tvb))
-
bool isFunctionType(Symbol::\label(_,Symbol lt))
-
bool isFunctionType(Symbol::\func(,,_))
-
default bool isFunctionType(Symbol _)
Determine if the given type is a function.
1.16.50. isReifiedType
-
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 _)
Determine if the given type is a reified type.
1.16.51. isTypeVar
-
bool isTypeVar(Symbol::\parameter(,))
-
bool isTypeVar(Symbol::\alias(,,Symbol at))
-
bool isTypeVar(Symbol::\label(_,Symbol lt))
-
default bool isTypeVar(Symbol _)
Determine if the given type is an type variable (parameter).
1.17. ValueIO
import ValueIO;
Library functions for reading and writing values in textual and binary format.
1.17.1. readValueFile
value readValueFile(loc file)
Read a value from a binary file in PBF format.
1.17.2. getFileLength
int getFileLength(loc file)
Get length of a file in number of bytes.
1.17.3. readBinaryValueFile
-
&T readBinaryValueFile(type[&T] result, loc file)
-
value readBinaryValueFile(loc file)
Read a typed value from a binary file.
1.17.4. readTextValueFile
-
&T readTextValueFile(type[&T] result, loc file)
-
value readTextValueFile(loc file)
Read a typed value from a text file.
1.17.5. readTextValueFileWithEmbeddedTypes
&T readTextValueFileWithEmbeddedTypes(type[&T] result, loc file)
If you have written a file containing reified types, then you can use this function to read them back.
1.17.6. readTextValueString
-
value readTextValueString(str input)
-
&T readTextValueString(type[&T] result, str input)
Parse a textual string representation of a value.
1.17.7. writeBinaryValueFile
void writeBinaryValueFile(loc file, value val, bool compression = true)
Write a value to a file using an efficient binary file format.
1.17.8. writeTextValueFile
void writeTextValueFile(loc file, value val)
Write a value to a file using a textual file format.
2. analysis
Library functions for analysis tasks.
-
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.
-
Correlation: Correlation between data values.
-
Descriptive: Descriptive Statistics.
-
Frequency: Frequency distributions.
-
Inference: Statistical inference methods.
-
SimpleRegression: Statistical methods for simple regression.
-
2.1. FCA
import analysis::formalconcepts::FCA;
Library for Formal Concept Analysis
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
ConceptLattice[&Object, &Attribute] fca (FormalContext[&Object, &Attribute] fc)
Computes Concept Lattice given the Object Attribute Relation.
2.1.2. toDot
-
DotGraph toDot(ConceptLattice[&Object, &Attribute] cl)
-
DotGraph toDot(ConceptLattice[&Object, &Attribute] cl, bool lab)
Computes Dot Graph from Concept Lattice.
2.1.3. toDotline
Dotline toDotline(ConceptLattice[&Object, &Attribute] cl)
2.1.4. toOutline
Outline toOutline(ConceptLattice[&Object, &Attribute] cl)
2.1.5. toFormalContext
-
FormalContext[&Object, &Attribute] toFormalContext(Object2Attributes[&Object, &Attribute] objects)
-
FormalContext[&Object, &Attribute] toFormalContext(Attribute2Objects[&Object, &Attribute] attributes)
2.1.6. intersection
set[&T] intersection(set[set[&T]] st)
2.1.7. union
set[&T] union(set[set[&T]] st)
2.1.8. isSubset
bool isSubset(set[set[&T]] candidate, set[&T] s )
2.1.9. sigma
set[&Attribute] sigma(FormalContext[&Object, &Attribute] fc, set[&Object] objects)
2.1.10. tau
set[&Object] tau(FormalContext[&Object, &Attribute] fc, set[&Attributes] attributes)
2.1.11. maxincl
set[set[&T]] maxincl(set[set[&T]] c)
2.1.12. createAttributeLattice
rel[set[&Attribute], set[&Attribute]] createAttributeLattice(FormalContext[&Object, &Attribute] fc)
2.1.13. makeNodes
map[Concept[&Object, &Attribute], int] makeNodes(ConceptLattice[&Object, &Attribute] q)
2.1.14. newAdded1
set[&Attribute] newAdded1(ConceptLattice[&Object, &Attribute] q, Concept[&Object, &Attribute] c)
2.1.15. newAdded0
set[Concept[&Object, &Attribute]] newAdded0(ConceptLattice[&Object, &Attribute] q, Concept[&Object, &Attribute] c)
2.1.16. compose
Stm compose(Concept[&Object, &Attribute] c, map[Concept[&Object, &Attribute], int] z, bool lab)
2.1.17. toDotString
str toDotString(ConceptLattice[&Object, &Attribute] q)
Write relation in .dot
format.
2.2. graphs
Analyzing unlabeled and labelled graphs.
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
import analysis::graphs::Graph;
A Graph
datatype with associated functions.
alias Graph[&T] = rel[&T from, &T to];
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:
-
order: Compute topological order of the nodes in a graph.
-
stronglyConnectedComponents: Compute strongly connected components in a graph.
-
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
list[&T] order(Graph[&T] g)
Compute topological order of the nodes in a graph.
rascal>import analysis::graphs::Graph;
ok
rascal>order({<3,4>, <1,2>, <2,4>, <1,3>});
list[int]: [1,2,3,4]
stronglyConnectedComponents
set[set[&T]] stronglyConnectedComponents(Graph[&T] g)
Compute strongly connected components in a graph.
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
tuple[set[set[&T]], list[&T]] stronglyConnectedComponentsAndTopSort(Graph[&T] ag)
bottom
set[&T] bottom(Graph[&T] G)
Determine the bottom nodes (leaves) of a graph.
Returns the bottom nodes of Graph G
, i.e., the leaf nodes that don’t have any descendants.
rascal>import analysis::graphs::Graph;
ok
rascal>bottom({<1,2>, <1,3>, <2,4>, <3,4>});
set[int]: {4}
predecessors
set[&T] predecessors(Graph[&T] G, &T From)
Determine the direct predecessors of a graph node.
Returns the direct predecessors of node From
in Graph G
.
rascal>import analysis::graphs::Graph;
ok
rascal>predecessors({<1,2>, <1,3>, <2,4>, <3,4>}, 4);
set[int]: {3,2}
reach
set[&T] reach(Graph[&T] G, set[&T] Start)
Determine the graph nodes reachable from a set of nodes.
Returns the set of nodes in Graph G
that are reachable from any of the nodes in the set Start
.
reachR
set[&T] reachR(Graph[&T] G, set[&T] Start, set[&T] Restr)
Determine the graph nodes reachable from a set of nodes using a restricted set of intermediate nodes.
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
.
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
set[&T] reachX(Graph[&T] G, set[&T] Start, set[&T] Excl)
Determine the graph nodes reachable from a set of nodes excluding certain intermediate nodes.
Returns set of nodes in Graph G
that are reachable from any of the nodes in Start
via path that exclude nodes in Excl
.
rascal>import analysis::graphs::Graph;
ok
rascal>reachX({<1,2>, <1,3>, <2,4>, <3,4>}, {1}, {2});
set[int]: {3,4}
shortestPathPair
list[&T] shortestPathPair(Graph[&T] G, &T From, &T To)
Determine the shortest path between two graph nodes.
Returns the shortest path between nodes From
and To
in Graph G
.
successors
set[&T] successors(Graph[&T] G, &T From)
Determine the direct successors of a graph node.
Returns the direct successors of node From
in Graph G
.
rascal>import analysis::graphs::Graph;
ok
rascal>successors({<1,2>, <1,3>, <2,4>, <3,4>}, 1);
set[int]: {3,2}
top
set[&T] top(Graph[&T] G)
Determine the set of top nodes (roots) of a graph.
Returns the top nodes of Graph G
, i.e., the root nodes that do not have any predecessors.
rascal>import analysis::graphs::Graph;
ok
rascal>top({<1,2>, <1,3>, <2,4>, <3,4>});
set[int]: {1}
connectedComponents
set[set[&T]] connectedComponents(Graph[&T] G)
Determine the connected components of a graph.
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.
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
import analysis::graphs::LabeledGraph;
[[LabeledGraph-LGraph[&T,&L]]] ## LGraph[&T,&L] .Types
rel[&T from, &L label, &T to]
bottom
set[&T] bottom(LGraph[&T,&L] G)
Return the bottom nodes of a LGraph.
predecessors
set[&T] predecessors(LGraph[&T,&L] G, &T From)
The predecessors of a single node in a LGraph.
reach
set[&T] reach(LGraph[&T,&L] G, set[&T] Start)
Reachability from a given start set of nodes.
reachR
set[&T] reachR(LGraph[&T,&L] G, set[&T] Start, set[&T] Restr)
Reachability from given start set of nodes with restrictions.
reachX
set[&T] reachX(LGraph[&T,&L] G, set[&T] Start, set[&T] Excl)
Reachability from given start set of nodes with exclusions.
successors
set[&T] successors(LGraph[&T, &L] G, &T From)
The successors of a single node in a LGraph.
top
set[&T] top(LGraph[&T,&L] G)
Return the top nodes of a LGraph.
2.3. m3
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]
-
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
Statistical functions.
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:
-
Statistics on Wikipedia.
-
An Introduction to Statistics by Keone Hon.
-
Think Stats: Probability and Statistics for Programmers] by Allan B. Downey gives a very readable overview of statistic techniques.
-
Statistics Calculator allows entering data and get an overview of the values of various statistical indicators.
-
Online Calculation on STATISTICS gives calculators for individual measures.
The following functionality is offered:
-
Correlation: Correlation between data values.
-
Descriptive: Descriptive Statistics.
-
Frequency: Frequency distributions.
-
Inference: Statistical inference methods.
-
SimpleRegression: Statistical methods for simple regression.
-
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
import analysis::statistics::Correlation;
Correlation between data values.
Compute the correlation between pairs of data values. Correlation measures the statistical relationship between two sets of data.
The following functions are provided:
-
PearsonsCorrelation: Pearson product-moment correlation coefficient.
-
PearsonsCorrelationStandardErrors: Standard errors associated with Pearson correlation
-
PearsonsCorrelationPValues: P-values (significance) associated with Pearson correlation
-
SpearmansCorrelation: Spearman’s rank correlation coefficient.
-
covariance: Covariance of data values.
PearsonsCorrelation
num PearsonsCorrelation(lrel[num x,num y] values)
Pearson product-moment correlation coefficient.
Compute the Pearson product-moment correlation coefficient. It is a measure of the strength of the linear dependence between two variables.
Use SpearmansCorrelation when there is a monotonous dependence between the two variables.
PearsonsCorrelationStandardErrors
list[real] PearsonsCorrelationStandardErrors(lrel[num x,num y] values)
Standard errors associated with Pearson correlation.
PearsonsCorrelationPValues
list[real] PearsonsCorrelationPValues(lrel[num x,num y] values)
P-values (significance) associated with Pearson correlation.
SpearmansCorrelation
num SpearmansCorrelation(lrel[num x,num y] values)
Spearman’s rank correlation coefficient.
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.
Use PearsonsCorrelation when there is a linear dependence between the variables.
covariance
num covariance(lrel[num x,num y] values)
Covariance of data values.
Computes the covariance between the x
and y
values.
rascal>import analysis::statistics::Correlation;
ok
rascal>covariance([<1,12>,<3,12>,<3,11>,<5,7>]);
num: -2.5
2.4.2. Descriptive
import analysis::statistics::Descriptive;
Descriptive Statistics.
Provides the following univariate (single variable) statistics functions:
-
geometricMean: Geometric mean of data values.
-
kurtosis: Kurtosis of data values.
-
kurtosisExcess: Kurtosis excess of data values.
-
max: Largest data value
-
mean: Arithmetic mean of data values.
-
median: Median of data values.
-
min: Smallest data value
-
percentile: Percentile of data values.
-
variance: Variance of data values.
-
skewness: Skewness of data values.
-
standardDeviation: Standard deviation of data values.
-
sum: Sum of data values
-
sumsq: Sum of the squares of data values
-
centralMoment: Calculate the k-th central momen
-
moment: Calculate the k-th momen
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
real geometricMean([num hd, *num tl])
Geometric mean of data values.
Computes the geometric mean of the given data values.
kurtosis
real kurtosis(list[num] values:[, *])
Kurtosis of data values.
Computes the kurtosis of the given data values. Kurtosis is a measure of the "peakedness" of a distribution.
kurtosisExcess
real kurtosisExcess(list[num] values)
Kurtosis excess of data values.
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
(&T <: num) max([(&T <: num) h, *(&T <: num) t])
Largest data value.
mean
real mean(list[num] nums:[, *])
Arithmetic mean of data values.
Computes the arithmetic mean of the data values.
median
default real median(list[num] nums:[, *])
Median of data values.
Returns the median of the available values. This is the same as the 50th [percentile].
rascal>import analysis::statistics::Descriptive;
ok
rascal>median([1,2,5,7,8]);
real: 5.
rascal>median([1,2,2,6,7,8]);
real: 4.
middle
list[&T] middle(list[&T] nums)
min
(&T <: num) min([(&T <: num) h, *(&T <: num) t])
Smallest data value.
percentile
&T <: num percentile(list[&T <: num] nums, num p)
Percentile of data values.
Returns the p`th percentile of the data values. 0 < `p
⇐ 100 should hold.
variance
num variance([num hd, *num tl])
Variance of data values.
Computes the variance of the data values. It measures how far a set of numbers is spread out.
skewness
real skewness(list[num] values:[, *])
Skewness of data values.
Returns the skewness of the available values. Skewness is a measure of the asymmetry of a given distribution.
standardDeviation
real standardDeviation(list[num] values)
Standard deviation of data values.
Computes the standard deviation of the data values. It shows how much variation exists from the average (mean, or expected value).
sum
(&T <:num) sum([(&T <: num) hd, *(&T <: num) tl])
Sum of data values.
sumsq
(&T <:num) sumsq(list[&T <:num] values)
Sum of the squares of data values.
centralMoment
real centralMoment(list[num] nums:[, *], int order = 1)
Calculate the k-th central moment
moment
real moment(list[num] nums:[, *], int order = 1)
Calculate the k-th moment
2.4.3. Frequency
import analysis::statistics::Frequency;
Frequency distributions.
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
-
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)
Compute a distribution: count how many times events are mapped to which bucket.
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
-
int cumFreq(list[value] values, num n)
-
int cumFreq(list[value] values, str s)
Cumulative frequency of values less than or equal to a given value.
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.
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
-
num cumPct(list[value] values, num n)
-
num cumPct(list[value] values, str s)
Cumulative percentage of values less than or equal to a given value.
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
-
num pct(list[value] values, num n)
-
num pct(list[value] values, str s)
Percentage of values that are equal to a given value.
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
import analysis::statistics::Inference;
Statistical inference methods.
The following functions are provided:
-
chiSquare: Chi-square coefficient of data values.
-
chiSquareTest: Chi-square test on data values.
-
tTest: T-test on sample data.
-
anovaFValue: Analysis of Variance (ANOVA) f-value.
-
anovaPValue: Analysis of Variance (ANOVA) p-value.
-
anovaTest: Analysis of Variance (ANOVA) test.
-
gini: Gini coefficient.
chiSquare
num chiSquare(lrel[num expected, int observed] values)
Chi-square coefficient of data values.
Compute the ChiSquare statistic comparing observed and expected frequency counts.
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
-
num chiSquareTest(lrel[num expected, int observed] values)
-
bool chiSquareTest(lrel[num expected, int observed] values, real alpha)
Chi-square test on data values.
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
-
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)
T-test on sample data.
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
andsample2
are drawn from populations with the same mean, with significance levelalpha
. 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, usealpha
/ 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, usealpha
* 2.
-
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
num anovaFValue(list[list[num]] categoryData)
Analysis of Variance (ANOVA) f-value.
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
num anovaPValue(list[list[num]] categoryData)
Analysis of Variance (ANOVA) p-value.
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
bool anovaTest(list[list[num]] categoryData, num alpha)
Analysis of Variance (ANOVA) test.
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
real gini(lrel[num observation,int frequency] values)
Gini coefficient.
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).
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
import analysis::statistics::SimpleRegression;
Statistical methods for simple regression.
The following functions are provided:
-
intercept: Intercept of regression line.
-
interceptStdErr: Standard error of intercept estimate.
-
meanSquareError: Sum of squared errors divided by the degrees of freedom.
-
R: Pearson’s product-moment correlation coefficient.
-
regressionSumSquares: Sum of squared deviations of the predicted y values about their mean.
-
RSquare: Coefficient of determination.
-
significance: Significance of the slope correlation.
-
slope: Slope of regression line.
-
slopeConfidenceInterval: The 95% slope confidence interval.
-
slopeStdErr: Standard error of slope estimate.
-
sumOfCrossProducts: Sum of cross products of observations.
-
sumSquaredErrors: Sum of squared errors.
-
totalSumSquares: Sum of squared deviations.
-
XSumSquares: Sum of squared deviations of x values about their mean.
-
predict: Predict a value.
intercept
num intercept(lrel[num,num] values) throws IllegalArgument
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
num interceptStdErr(lrel[num,num] values) throws IllegalArgument
Standard error of intercept estimate. .Description Returns the standard error of the intercept estimate, usually denoted s(b0).
meanSquareError
num meanSquareError(lrel[num,num] values) throws IllegalArgument
Sum of squared errors divided by the degrees of freedom.
Returns the sum of squared errors divided by the degrees of freedom, usually abbreviated MSE.
R
num R(lrel[num,num] values) throws IllegalArgument
Pearson’s product-moment correlation coefficient.
Computes Pearson’s product-moment correlation coefficient. More functions related to this coefficient can be found in Correlation.
regressionSumSquares
num regressionSumSquares(list[tuple[num,num]] values) throws IllegalArgument
Sum of squared deviations of the predicted y values about their mean.
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
num RSquare(lrel[num,num] values) throws IllegalArgument
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
num significance(lrel[num,num] values) throws IllegalArgument
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)
The validity of this statistic depends on the assumption that the observations included in the model are drawn from a Bivariate Normal Distribution.
slope
num slope(lrel[num,num] values) throws IllegalArgument
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
num slopeConfidenceInterval(lrel[num,num] values) throws IllegalArgument
The 95% slope confidence interval.
Returns the half-width of a 95% confidence interval for the slope estimate. The 95% confidence interval is
(slope - slopeConfidenceInterval, slope + slopeConfidenceInterval)
The validity of this statistic depends on the assumption that the observations included in the model are drawn from a Bivariate Normal Distribution.
slopeStdErr
num slopeStdErr(lrel[num,num] values) throws IllegalArgument
Standard error of slope estimate. .Description
Returns the standard error of the slope estimate, usually denoted s(b1).
sumOfCrossProducts
num sumOfCrossProducts(lrel[num,num] values) throws IllegalArgument
Sum of cross products of observations. .Description
Returns the sum of crossproducts, xi*yi.
sumSquaredErrors
num sumSquaredErrors(lrel[num,num] values) throws IllegalArgument
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
num totalSumSquares(lrel[num,num] values) throws IllegalArgument
Sum of squared deviations. .Description
Returns the sum of squared deviations of the y values about their mean. This is defined as SSTO.
XSumSquares
num XSumSquares(lrel[num,num] values) throws IllegalArgument
Sum of squared deviations of x values about their mean.
Returns the sum of squared deviations of the x values about their mean.
predict
num predict(lrel[num,num] values, num x) throws IllegalArgument
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
Definitions and tools for various languages.
3.1. RSF
Functions for reading/writing the Rigi Standard Format (RSF).
import lang::RSF::IO;
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).
call main printf
call main listcreate
data main FILE
data listcreate List
defines two relations named call
and data
.
3.1.1. readRSF
Read a file in Rigi Standard Format (RSF).
map[str, rel[str,str]] readRSF(str nameRSFFile) throws IO(str msg)
Since an RSF file may define more than one relation, a mapping from relation name to relation value is returned.
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
Comma-Separated Values (CSV).
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:
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
Definitions and tools related to the Java language.
3.3.1. jdt
tools for Java provided via reusing the Eclipse JDT
m3
functions for generating M3 models starting from Eclipse projects
3.3.2. m3
Java-specific version of the M3 model
This API extends m3 with Java specific functionality:
Use this API to extract Java m3 models starting from Eclipse Java projects:
AST
import lang::java::m3::AST;
defines AST node types for Java
Declaration
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
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
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
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
data Modifier
= \private()
| \public()
| \protected()
| \friendly()
| \static()
| \final()
| \synchronized()
| \transient()
| \abstract()
| \native()
| \volatile()
| \strictfp()
| \annotation(Expression \anno)
| \onDemand()
| \default()
;
getPaths
set[loc] getPaths(loc dir, str suffix)
findRoots
set[loc] findRoots(set[loc] folders)
createAstFromFile
Declaration createAstFromFile(loc file, bool collectBindings, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")
Creates AST from a file
createAstsFromFiles
set[Declaration] createAstsFromFiles(set[loc] file, bool collectBindings, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")
Creates AST from a file
createAstFromString
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
set[Declaration] createAstsFromDirectory(loc project, bool collectBindings, bool errorRecovery = false, str javaVersion = "1.7" )
Creates ASTs from a project
Core
import lang::java::m3::Core;
extends the M3 [$analysis/m3/Core] with Java specific concepts such as inheritance and overriding.
For a quick start, go find [createM3FromEclipseProject].
M3
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
data Language (str version="")
= java()
;
composeJavaM3
M3 composeJavaM3(loc id, set[M3] models)
diffJavaM3
M3 diffJavaM3(loc id, list[M3] models)
createM3FromFile
M3 createM3FromFile(loc file, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")
createM3sFromFiles
set[M3] createM3sFromFiles(set[loc] files, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")
createM3FromFiles
M3 createM3FromFiles(loc projectName, set[loc] files, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")
createM3sAndAstsFromFiles
tuple[set[M3], set[Declaration]] createM3sAndAstsFromFiles(set[loc] files, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")
createM3FromString
M3 createM3FromString(loc fileName, str contents, bool errorRecovery = false, list[loc] sourcePath = [], list[loc] classPath = [], str javaVersion = "1.7")
createM3FromJarClass
M3 createM3FromJarClass(loc jarClass, list[loc] classPath = [])
createM3FromSingleClass
M3 createM3FromSingleClass(loc jarClass, str className)
createM3FromJarFile
M3 createM3FromJarFile(loc jarLoc, list[loc] classPath = [])
createM3FromDirectory
M3 createM3FromDirectory(loc project, bool errorRecovery = false, str javaVersion = "1.7", list[loc] classPath = [])
globs for jars, class files and java files in a directory and tries to compile all source files into an [$analysis/m3] model
createM3FromJar
M3 createM3FromJar(loc jarFile, list[loc] classPath = [])
unregisterJavaProject
void unregisterJavaProject(loc project)
getMethodSignature
str getMethodSignature(loc method)
isCompilationUnit
bool isCompilationUnit(loc entity)
isPackage
bool isPackage(loc entity)
isClass
bool isClass(loc entity)
isConstructor
bool isConstructor(loc entity)
isMethod
bool isMethod(loc entity)
isParameter
bool isParameter(loc entity)
isVariable
bool isVariable(loc entity)
isField
bool isField(loc entity)
isInterface
bool isInterface(loc entity)
isEnum
bool isEnum(loc entity)
isType
bool isType(loc entity)
files
set[loc] files(rel[loc, loc] containment)
declaredMethods
rel[loc, loc] declaredMethods(M3 m, set[Modifier] checkModifiers = {})
declaredFields
rel[loc, loc] declaredFields(M3 m, set[Modifier] checkModifiers = {})
declaredFieldsX
rel[loc, loc] declaredFieldsX(M3 m, set[Modifier] checkModifiers = {})
declaredTopTypes
rel[loc, loc] declaredTopTypes(M3 m)
declaredSubTypes
rel[loc, loc] declaredSubTypes(M3 m)
classes
set[loc] classes(M3 m)
interfaces
set[loc] interfaces(M3 m)
packages
set[loc] packages(M3 m)
variables
set[loc] variables(M3 m)
parameters
set[loc] parameters(M3 m)
fields
set[loc] fields(M3 m)
methods
set[loc] methods(M3 m)
constructors
set[loc] constructors(M3 m)
enums
set[loc] enums(M3 m)
types
set[loc] types(M3 m)
elements
set[loc] elements(M3 m, loc parent)
fields
set[loc] fields(M3 m, loc class)
methods
set[loc] methods(M3 m, loc class)
constructors
set[loc] constructors(M3 m, loc class)
nestedClasses
set[loc] nestedClasses(M3 m, loc class)
<AUTOINSERTED>
typeDependency
anno rel[loc from, loc to] M3@typeDependency;
</AUTOINSERTED>
TypeHierarchy
import lang::java::m3::TypeHierarchy;
getDeclaredTypeHierarchy
rel[loc from, loc to] getDeclaredTypeHierarchy(M3 model)
TypeSymbol
import lang::java::m3::TypeSymbol;
Bound
data Bound
= \super(list[TypeSymbol] bound)
| \extends(list[TypeSymbol] bound)
| \unbounded()
;
TypeSymbol
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
default bool subtype(TypeSymbol s, TypeSymbol t)
lub
default TypeSymbol lub(TypeSymbol s, TypeSymbol t)
3.4. xml
XML utilities
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
Utilities: functions, data types and interfaces with external libraries.
-
Benchmark: Functions for time measurement and benchmarking.
-
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. -
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
import util::Benchmark;
Functions for time measurement and benchmarking.
The Benchmark
library provides the following functions:
-
heapDump: Write a JVM heap dump to a file.
-
cpuTime: CPU time in nanoseconds (10-9 sec).
-
systemTime: System time in nanoseconds (10-9 sec).
-
userTime: User time in nanoseconds (10-9 sec).
-
realTime: Current time in milliseconds (10-3 sec).
-
benchmark: Measure and report the execution time of name:void-closure pairs
-
getNanoTime: Current time in nanoseconds (10-9 sec) since January 1, 1970 GMT.
-
getMilliTime: Current time in milliseconds (10-3 sec) since January 1, 1970 GMT.
-
gc: Force a garbage collection.
4.1.1. heapDump
void heapDump(loc file, bool live=true)
Write a JVM heap dump to a file.
-
The file parameter has to be of the
file
scheme. -
The live parameter restricts the dump to only live objects.
4.1.2. cpuTime
-
int cpuTime()
-
int cpuTime(void () block)
CPU time in nanoseconds (10-9 sec).
-
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
.
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: 53330136606
rascal>fac(50);
int: 30414093201713378043612608166064768844377641568960512000000000000
rascal>cpuTime() - before;
int: 1386932
The code to be measured can also be passed as a function parameter to cpuTime
:
rascal>cpuTime( void() { fac(50); } );
int: 398502
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
-
int systemTime()
-
int systemTime(void () block)
System time in nanoseconds (10-9 sec).
-
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
.
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: 982187154
rascal>fac(50);
int: 30414093201713378043612608166064768844377641568960512000000000000
rascal>systemTime() - before;
int: 1537577
The code to be measured can also be passed as a function parameter to systemTime
:
rascal>systemTime( void() { fac(50); } );
int: 297229
4.1.4. userTime
-
int userTime()
-
int userTime(void () block)
User time in nanoseconds (10-9 sec).
-
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
.
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: 52390000000
rascal>fac(50);
int: 30414093201713378043612608166064768844377641568960512000000000000
rascal>userTime() - before;
int: 0
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
-
int realTime()
-
int realTime(void () block)
Current time in milliseconds (10-3 sec).
-
Current system time in milliseconds (10-3 sec) since January 1, 1970 GMT.
-
Real time in milliseconds needed to execute the code
block
.
4.1.6. benchmark
-
map[str,num] benchmark(map[str, void()] Cases)
-
map[str,num] benchmark(map[str, void()] Cases, int (void ()) duration)
Measure and report the execution time of name:void-closure pairs
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.
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);}) );
|std:///util/Benchmark.rsc|(6329,8,<227,25>,<227,33>): CallFailed([
("fac100":function(|prompt:///|(23,18,<1,23>,<1,41>)),"fac200":function(|prompt:///|(54,18,<1,54>,<1,72>))),
choice(
[
function(|std:///util/Benchmark.rsc|(4443,539,<169,0>,<187,27>)),
function(|std:///util/Benchmark.rsc|(5075,103,<192,0>,<196,1>))
],
[])
])
at benchmark(|std:///util/Benchmark.rsc|(6312,27,<227,8>,<227,35>))
at $shell$(|prompt:///|(0,76,<1,0>,<1,76>))
ok
WARNING: unexpected errors in the above SHELL example. Documentation author please fix! We can do the same using userTime that returns nanoseconds:
rascal>benchmark( ("fac100" : void() {fac(100);}, "fac200" : void() {fac(200);}), userTime );
|prompt:///|(75,8,<1,75>,<1,83>): CallFailed([
("fac100":function(|prompt:///|(23,18,<1,23>,<1,41>)),"fac200":function(|prompt:///|(54,18,<1,54>,<1,72>))),
choice(
[
function(|std:///util/Benchmark.rsc|(3339,906,<127,0>,<160,27>)),
function(|std:///util/Benchmark.rsc|(4338,103,<163,0>,<167,1>))
],
[])
])
at $shell$(|prompt:///|(0,86,<1,0>,<1,86>))
ok
WARNING: unexpected errors in the above SHELL example. Documentation author please fix!
4.1.7. getNanoTime
int getNanoTime()
Current time in nanoseconds (10-9 sec) since January 1, 1970 GMT. .Description
4.1.8. getMilliTime
int getMilliTime()
Current time in milliseconds (10-3 sec) since January 1, 1970 GMT.
This function is a synonym for realTime and gives the wall clock time in milliseconds.
4.1.9. gc
int gc()
Force a garbage collection.
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
import util::Eval;
4.3.1. Result
data Result[&T]
= ok()
| result(&T val)
;
4.3.2. Exception
data Exception
= StaticError(str message, loc location)
;
4.3.3. eval
-
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)
Evaluate a (list of) Rascal commands and return the value of the last command.
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.
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
-
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
Evaluate a (list of) Rascal commands and return the type of the last command.
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.
rascal>import util::Eval;
ok
rascal>evalType("2 * 3;");
str: "int"
rascal>evalType("[1, 2, 3];");
str: "list[int]"
4.4. Math
import util::Math;
Mathematical functions.
The Math
library provides the following functions:
-
abs: Absolute value of a number.
-
arbInt: Generate a random integer value.
-
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.
-
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).
-
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
4.4.1. abs
&T <: num abs(&T <: num N)
Absolute value of a number.
Absolute value of the number n
. The result type is equal to the type of the argument n
.
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
-
int arbInt()
-
int arbInt(int limit)
Generate a random integer value.
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.
rascal>import util::Math;
ok
rascal>arbInt();
int: 1270307031
rascal>arbInt();
int: 33623552
rascal>arbInt();
int: -475332367
rascal>arbInt(10);
int: 9
rascal>arbInt(10);
int: 3
rascal>arbInt(10);
int: 1
arbInt
is a convenient generator for pseudo-random integers.
4.4.3. arbReal
real arbReal()
Generate a random real value in the interval [0.0,1.0).
Generates an arbitrary real value in the interval [0.0, 1.0].
rascal>import util::Math;
ok
rascal>arbReal();
real: 0.11481438288832868
rascal>arbReal();
real: 0.7409396071493424
rascal>arbReal();
real: 0.4260230929466612
4.4.4. arbSeed
void arbSeed(int seed)
Define the seed for the generation of arbitrary values.
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
-
rat arbRat()
-
rat arbRat(int limit1, int limit2)
Generate an arbitrary rational value.
rascal>import util::Math;
ok
rascal>arbRat();
rat: 1095107579r1488967200
rascal>arbRat();
rat: 1072386599r1030851981
rascal>arbRat();
rat: -202822735r1055075479
rascal>arbRat(10,100);
rat: 0r
rascal>arbRat(10,100);
rat: 1r30
rascal>arbRat(10,100);
rat: 6r13
4.4.6. ceil
int ceil(num x)
Compute the smallest integer that is larger than a given number.
Computes the ceiling of a given number. Also see floor.
rascal>import util::Math;
ok
rascal>ceil(3.2);
int: 4
rascal>ceil(-3.2);
int: -3
4.4.7. cos
real cos(num x)
Calculate the cosine of a numeric value.
The cosine of the number x
.
rascal>import util::Math;
ok
rascal>cos(1.0)
real: 0.54030230588
rascal>cos(60 * PI() / 180)
real: 0.50000000000
4.4.8. denominator
int denominator(rat n)
Return the denominator of a rational value.
4.4.9. E
real E()
The constant E.
rascal>import util::Math;
ok
rascal>E();
real: 2.7182818285
4.4.10. exp
real exp(num x)
Compute exp(x). .Description Calculate e
<sup>`x`</sup>.
4.4.11. floor
int floor(num x)
Compute the largest integer that is smaller than a given number.
Computes the floor of a given number. Also see ceil.
rascal>import util::Math;
ok
rascal>floor(3.2);
int: 3
rascal>floor(-3.2);
int: -4
4.4.12. ln
real ln(num x)
Calculate the natural log of a numeric value.
Calculate natural log of x
.
rascal>import util::Math;
ok
rascal>ln(20.0)
real: 2.9957322736
rascal>ln(42.0)
real: 3.7376696183
4.4.13. log
real log(num x, num base)
Calculate the log<sub>base</sub> of a numeric value.
Calculate log<sub>base</sub> of x
.
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
real log10(num x)
Compute the 10 based log(x).
4.4.15. log2
real log2(num x)
Compute the 2 based log(x).
4.4.16. max
&T <: num max(&T <: num N, &T <: num M)
Determine the largest of two numeric values.
The largest of two numbers. The type of the result is the same as the type of the largest argument.
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
&T <: num min(&T <: num N, &T <: num M)
Determine the smallest of two numeric values.
The smallest of two numbers. The type of the result is the same as the type of the smallest argument.
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
int numerator(rat n)
Return the numerator of a rational value.
4.4.19. nroot
real nroot(num x, int n)
Calculate the n<sup>th</sup> root of a numeric value.
Calculate <sup>n</sup>√`x` where n
can only be a integer.
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
real PI()
The constant pi.
rascal>import util::Math;
ok
rascal>PI();
real: 3.1415926536
4.4.21. pow
-
real pow(num x, int y)
-
real pow(num x, real y)
Calculate an arbitrary power of a numeric value.
The calculate x
<sup>`y`</sup> where y
can only be a integer.
rascal>import util::Math;
ok
rascal>pow(sqrt(42), 2)
real: 41.99999999989811976256
rascal>pow(12345678901234567890.0, 1000)
real: 327323519862176629730082067574716643439462300540185122220961832511288805718030910484304325108222843885957688250811158315340566475836232001571619541935415038796348602192296984423155079801992333140052863080750492018420590783574245411031311510942905796189450351912614510641741094491709589411239576756065619918176653289948094430880732479266853021246187981170634861333302200580872985856560855518977488511675544145006801675791138351985746678734387422142342185164278661836498313416561398901718399810114596984172777042303963800096899625199810241300878005585014082782334502894938457546968837522885101157892509894692459561354313786780532679517827353604060468681961209174542267424246240853816845886755294209996435433895294269712878992262721644106226890031664370462222706979715904672586297266460593551184450504665032451235999357222433465060299295477020462819514888057483551478759508444976793225466736775132290553092049866427876353526626065630474037490603570383940996843823967040247622022658439400707006053650592894261198654836654639504753542843560398908885522596433160079097075880850067383018892541529465995345763588872837837593907229770700976597566733884202506653739605059379401347861288230399126563406134764726379055786459406660737522798066830604288612726394086519909309338994703718119693639450620275447776806553594104597194048560725083279242120977189767528195495335507571774589656293544257012451347889004221446663952536972136269481724663158860532924322053397767933001924701437115740854657082984585991651836842229921223742828990473127280082431920682100750955123993671834387994643422520721282979578784909325571258649149109201827243509225859052305726449746668735118920743230654106301983770403775061147939915240771494456634249374454345250552415101593382958143513116801567849013973694567642919070533812941570184136127617255991655186770210261385873186409485713856293174509996217914589400976889855958713421577335212662218393411619879901532201876563269347123972872344497080886637930441651259141049569049804413000150297629676129305940405487092640315363913091042956266173352666027423873096773031569220441623779694026871629405544513139993091183726122490006827751752741076885620415211542317496941956676394754879276979814511653516542017832996653484412313736356363305261532812972679430377759838879013873699720739033015759349473652785594888893377041014822677972342113818352300626995374712448170130314174419289739529982021437898597025566184922042135782017301373340541840251886826793222171028600662975155228812797443522045892690780164900156894217461209188361915847649443941189447229439906721259825215932223371314915787322490148065038149065584317884221248098894972346389635965334847844894296983317214252456367600733903894880305858451738209033898028888738089429510748290579293786966511702526421636839023818144487303883796157019333481281590182592242664434310787411848124503254182702718762286778744163663752419726010543539695902378784425822053579035604233167402979429162902604120869094779466506794967733027126798330733504515320709935121379216936936503517150761677018393050209847312382660928887004146016965681452309940614395990071269237730777211494402285973401134347314396249658064535813498390390228707068969712346028221844247394911352355219205653068923998044169246696199205931532280062594043451189765555574643899576685276356280338555983266720699445887933479778575910620051014501087647914152552526207935492180262761720164698382158135451840846941977075240573647713026577508324564964050461276723248623764128711424186543354565805827986611623687766424190141159982065651733888853975873295262987666051724164426176971670664220786382312628833993735024432664073367706606256513404081195840674289520710497921821809284330939220609778362882454615392304832328664341446921914422579024146155571399642339764786384745922769575752043854715925941119782659099976703423673050490970007943369522561413084390356583974592565338819090682096052094155857739238468257491510074355659857818999361006574913097067978865657382215313176814231120597124842183478696513677197512045290255088756641096724459645973492430801864900314570449211289319281689687528990384602371132230192221449626569380251208…
4.4.22. precision
-
int precision(num x)
-
real precision(num x, int p)
Return the precision of a real number.
4.4.23. setPrecision
int setPrecision(int p)
Define the precision for numeric calculations; returns the previous precision.
4.4.24. scale
int scale(num x)
Return the scale of a real number.
4.4.25. unscaled
int unscaled(real x)
Return the unscaled integer of a real.
4.4.26. remainder
int remainder(rat n)
Return the remainder of dividing the numerator by the denominator.
4.4.27. round
-
int round(num d)
-
(&T <: num) round(&T <: num r, &T <: num nearest)
Round a number to the nearest multiple of a given number (default 1).
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
real fitFloat(real r) throws ArithmeticException
The function fitFloat converts the unlimited precision real into a JVM float value.
-
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);
-
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
real fitDouble(real r) throws ArithmeticException
The function fitDouble converts the unlimited precision real into a JVM double value.
-
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);
-
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
int percent(num part, num whole)
Compute the ratio between two numbers as a percentage.
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
real sin(num x)
Calculate the sine of a numeric value.
The sine of the number x
.
rascal>import util::Math;
ok
rascal>sin(0)
real: 0.
rascal>sin(PI() / 2)
real: 1.00000000000
4.4.32. sqrt
real sqrt(num x)
Calculate the square root of a numeric value.
Calculate √`x`.
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
real tan(num x)
Calculate the tangent of a numeric value.
The tangent of the number x
.
rascal>import util::Math;
ok
rascal>tan(45 * PI() / 180)
real: 1.0000000000
4.4.34. toInt
int toInt(num N)
Convert a numeric value to an integer.
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.
rascal>import util::Math;
ok
rascal>toInt(13)
int: 13
rascal>toInt(13.5)
int: 13
4.4.35. toRat
rat toRat(int numerator, int denominator)
Convert two numbers to a rational value (not supported on reals).
4.4.36. toReal
real toReal(num N)
Convert a numeric value to a real.
rascal>import util::Math;
ok
rascal>toReal(12)
real: 12.
rascal>toReal(3.14)
real: 3.14
4.4.37. toString
str toString(num N)
Convert a numeric value to a string.
rascal>import util::Math;
ok
rascal>toString(12)
str: "12"
rascal>toString(3.14)
str: "3.14"
4.4.38. primes
list[int] primes(int upTo)
generate prime numbers up to a maximum
4.4.39. arbPrime
int arbPrime(int upTo)
4.5. Monitor
import util::Monitor;
Monitor the progress of a task/job.
4.5.1. startJob
-
void startJob(str name)
-
void startJob(str name, int totalWork)
-
void startJob(str name, int workShare, int totalWork)
Log the start of a job.
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
-
void event(str name)
-
void event(str name, int inc)
-
void event(int inc)
Log the start of an event (it is ended by another event
or by endJob
).
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
int endJob(bool succeeded)
Log the end of a job.
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
void todo(int work)
Set the estimated remaining work for the current (sub)job.
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
import util::PriorityQueue;
A PriorityQueue
datatype and associated functions.
import util::PriorityQueue;
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:
Currently, both priority and associated value ("payload") have to be integers. This will be generalized.
4.6.1. BinomialTree
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
BinomialTree addSubTree(BinomialTree p, BinomialTree q)
4.6.3. mergeTree
BinomialTree mergeTree(BinomialTree p, BinomialTree q)
4.6.4. toString
str toString(BinomialTree T)
4.6.5. PriorityQueue
data PriorityQueue
= priorityQueue(list[BinomialTree] trees, // trees in the heap
int minIndex // index of minimal tree
)
;
4.6.6. mkPriorityQueue
-
PriorityQueue mkPriorityQueue()
-
PriorityQueue mkPriorityQueue(int priority, int val)
4.6.7. isEmpty
bool isEmpty(PriorityQueue Q)
4.6.8. insertElement
PriorityQueue insertElement(PriorityQueue Q, int priority, int val)
4.6.9. findMinimum
int findMinimum(PriorityQueue Q)
4.6.10. extractMinimum
tuple[int, int, PriorityQueue] extractMinimum(PriorityQueue Q)
4.6.11. toString
str toString(PriorityQueue Q)
4.6.12. add
list[BinomialTree] add(list[BinomialTree] heap, BinomialTree t)
4.6.13. mergeQueue
PriorityQueue mergeQueue(PriorityQueue p, PriorityQueue q)
4.7. Prompt
documentation awaits Eclipse integration |
4.8. Resources
A Resource
datatype and related functions on Eclipse resources.
import util::Resources;
data Resource = root(set[Resource] projects)
| project(loc id, set[Resource] contents)
| folder(loc id, set[Resource] contents)
| file(loc id);
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.
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
This library is only available for the Eclipse version of Rascal.
4.8.1. dependencies
Compute the (transitive) dependencies of a project.
set[loc] dependencies(loc project)
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
Retrieve the hierarchical representation of a single named project.
Resource getProject(loc project)
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
Retrieve the set of project locations of the current Eclipse workspace.
set[loc] projects()
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
The set of projects that are referenced by a project.
set[loc] references(loc project)
4.8.5. root
Retrieve a full hierarchical representation of all resources in the Eclipse workspace.
Resource root()
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
import util::ShellExec;
Execute and manage external processes.
4.9.1. createProcess
PID createProcess(str processCommand, loc workingDir=|cwd:///|, list[str] args = [], map[str,str] envVars = ())
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
str exec(str processCommand, loc workingDir=|cwd:///|, list[str] args = [], map[str,str] env = ())
start, run and kill an external process returning its output as a string.
4.17.2. killProcess
void killProcess(PID processId, bool force=false)
Kill a running process, or a zombie process (a process which is not alive yet not killed)
4.17.3. isAlive
bool isAlive(PID processId)
Check whether a process is still alive
4.17.4. isZombie
bool isZombie(PID processId)
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
str readFrom(PID processId)
Read from an existing process’s output stream. This is non-blocking.
4.17.6. readWithWait
str readWithWait(PID processId, int wait)
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
str readFromErr(PID processId)
Read from an existing process’s error output stream. This is non-blocking.
4.17.8. readLineFromErr
str readLineFromErr(PID processId, int wait=200, int maxTries=5)
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
str readEntireStream(PID processId)
Read the entire stream from an existing process’s output stream. This is blocking.
4.17.10. readEntireErrStream
str readEntireErrStream(PID processId)
Read the entire error stream from an existing process’s output stream. This is blocking.
4.17.11. writeTo
void writeTo(PID processId, str msg)
Write to an existing process’s input stream.
4.17.12. PID
int
Process Identifiers (PID).
A PID is returned by createProcess and is required for any further interaction with the created process.