library(RTypeInference)
This vignette demonstrates running type inference on a simple, non-recursive
function, fib()
, for calculating the n-th Fibonacci number:
fib = function(n) { .typeInfo(n = IntegerType()) acc = c(0, 0, 1) for (i in 1:n) { acc[1:2] = acc[2:3] acc[3] = sum(acc[1:2]) } return(acc[1]) }
The function .typeInfo()
is provided by RTypeInference
for annotating
argument types; it's defined as a no-op so that functions using it can still be
run in the R interpreter with minimal performance overhead. In the future, we
will also support annotating argument types using an attribute.
sapply(1:10, fib)
Two important details are that no type information is provided about the
variable acc
, and the function returns a subset of this variable. Moreover,
the type of the variable i
in the loop should not only be inferred, but also
marked as an iterator variable.
In order to hold on to the inferred types, we must first define a
TypeCollector
:
collector = TypeCollector()
Now we can infer the types of the function:
infer_types(fib, collector)
Although the vector acc
has numeric type in the R interpreter, its type is
inferred as integer because the initial values are all integers. Thus the
return type is inferred correctly. Note that the return value is marked as
unknown; for a constant function, the return value would be displayed.
To view the inferred types for the other variables, we have to print the
TypeCollector
object we defined earlier:
print(collector)
In the printout we can see that the inferred types for both acc
and i
are
correct. In particular, the variable i
is marked as an iterator variable with
atomic type integer.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.