5.2 FFI Helpers
There are a number of convenience functions that aren’t native to the Pyret runtime, but are often used in JavaScript code that interacts with the runtime. Some of the most commonly used ones are documented here; this list is often growing.
5.2.1 Equality
The ffi exposes several utilities related to equality.
The Equal value.
The Unknown value.
The NotEqual constructor.
Checks if the given value is Equal.
Checks if the given value is an instance of NotEqual.
Checks if the given value is a Unknown.
Checks if the given value is an instance of a EqualityResult.
5.2.2 Exceptions
FFI helpers provide the easiest way to programmatically throw Pyret exceptions from JavaScript. Most commonly, user-defined modules will simply throw MessageExceptions that contain a string describing the error.
Throws an exception that Pyret recognizes and reports with a stack trace, using the provided string as the message.
Sometimes its useful to create an exception without actually throwing it, like when using the error callback of the Restarter in Runtime.pauseStack. This call creates a new exception object without throwing it.
5.2.3 Lists
Pyret lists are ubiquitous in Pyret’s internals and libraries, and this library provides a few conveniences for working with them.
Turns a JavaScript array into a Pyret List with the same elements in the same order.
Turns a Pyret List with the same elements in the same order. For doing computationally heavy work, sometimes it is useful to convert a Pyret List to an array before processing it (and using JavaScript’s map/filter, etc.), since the Pyret version incurs more overhead.
Returns true if the value is a Pyret List and false otherwise.
5.2.4 Other Data Helpers
Create instances of none and some from option.
Create instances of left and right from either.
This call emulates the functionality of the cases expression in a JavaScript context. It takes a predicate to check (usually a function like is-List), a name for the predicate being checked, a data value, and an object containing handlers for its variants. For example:
function sum(l) { |
cases(runtime.getField(lists, "is-List"), "List", l, { |
empty: function() { return "Empty"; }, |
link: function(f, r) { return f + sum(r); } |
}); |
} |
sum(runtime.ffi.makeList([1,2])) // is 3 |
The predicate check and name are solely for error reporting.