-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.Rmd
347 lines (275 loc) · 7.92 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
---
output:
github_document:
html_preview: false
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
```{r, include = FALSE}
knitr::opts_chunk$set(
warning = FALSE,
message = FALSE,
fig.path = "man/figures/README-",
fig.align = "center",
out.width = "100%",
dpi = 75,
collapse = TRUE,
comment = "#>"
)
```
# interface
<!-- badges: start -->
[![R-CMD-check](https://github.com/dereckmezquita/interface/workflows/R-CMD-check/badge.svg)](https://github.com/dereckmezquita/interface/actions)
[![Lifecycle: experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://lifecycle.r-lib.org/articles/stages.html#experimental)
[![CRAN status](https://www.r-pkg.org/badges/version/interface)](https://CRAN.R-project.org/package=interface)
[![GitHub version](https://img.shields.io/github/r-package/v/dereckmezquita/interface?label=GitHub)](https://github.com/dereckmezquita/interface)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Downloads](https://cranlogs.r-pkg.org/badges/interface)](https://cran.r-project.org/package=interface)
<!-- badges: end -->
The `interface` package provides a system for defining and implementing interfaces in R, with runtime type checking, bringing some of the benefits of statically-typed languages to R with zero dependencies.
`interface` provides:
1. **Interfaces**: Define and implement interfaces with type checking. Interfaces can be extended and nested.
1. **Typed Functions**: Define functions with strict type constraints.
1. **Typed Frames**: Choose between a `data.frame` or `data.table` with column type constraints and row validation.
1. **Enums**: Define and use enumerated types for stricter type safety.
## Installation
Install the package from CRAN:
```{r eval = FALSE}
install.packages("interface")
```
Or install the latest development version from GitHub:
```{r eval = FALSE}
# Install the package from the source
remotes::install_github("dereckmezquita/interface")
```
## Getting started
Import the package functions.
```{r}
box::use(interface[ interface, type.frame, fun, enum ])
```
Define an interface and implement it:
```{r}
# Define an interface
Person <- interface(
name = character,
age = numeric,
email = character
)
# Implement the interface
john <- Person(
name = "John Doe",
age = 30,
email = "john@example.com"
)
print(john)
# interfaces are lists
print(john$name)
# Modify the object
john$age <- 10
print(john$age)
# Invalid assignment (throws error)
try(john$age <- "thirty")
```
### Extending Interfaces and Nested Interfaces
Create nested and extended interfaces:
```{r}
# Define nested interfaces
Address <- interface(
street = character,
city = character,
postal_code = character
)
Scholarship <- interface(
amount = numeric,
status = logical
)
# Extend interfaces
Student <- interface(
extends = c(Address, Person),
student_id = character,
scores = data.table::data.table,
scholarship = Scholarship
)
# Implement the extended interface
john_student <- Student(
name = "John Doe",
age = 30,
email = "john@example.com",
street = "123 Main St",
city = "Small town",
postal_code = "12345",
student_id = "123456",
scores = data.table::data.table(
subject = c("Math", "Science"),
score = c(95, 88)
),
scholarship = Scholarship(
amount = 5000,
status = TRUE
)
)
print(john_student)
```
### Custom Validation Functions
Interfaces can have custom validation functions:
```{r}
is_valid_email <- function(x) {
grepl("[a-z|0-9]+\\@[a-z|0-9]+\\.[a-z|0-9]+", x)
}
UserProfile <- interface(
username = character,
email = is_valid_email,
age = function(x) is.numeric(x) && x >= 18
)
# Implement with valid data
valid_user <- UserProfile(
username = "john_doe",
email = "john@example.com",
age = 25
)
print(valid_user)
# Invalid implementation (throws error)
try(UserProfile(
username = "jane_doe",
email = "not_an_email",
age = "30"
))
```
### Typed Functions
Define functions with strict type constraints:
```{r}
typed_fun <- fun(
x = numeric,
y = numeric,
return = numeric,
impl = function(x, y) {
return(x + y)
}
)
print(typed_fun(1, 2)) # [1] 3
try(typed_fun("a", 2)) # Invalid call
```
Functions with multiple possible return types:
```{r}
typed_fun2 <- fun(
x = c(numeric, character),
y = numeric,
return = c(numeric, character),
impl = function(x, y) {
if (is.numeric(x)) {
return(x + y)
} else {
return(paste(x, y))
}
}
)
print(typed_fun2(1, 2)) # [1] 3
print(typed_fun2("a", 2)) # [1] "a 2"
```
### Typed `data.frame`s and `data.table`s
Create `data.frame`s with column type constraints and row validation:
```{r}
PersonFrame <- type.frame(
frame = data.frame,
col_types = list(
id = integer,
name = character,
age = numeric,
is_student = logical
)
)
# Create a data frame
persons <- PersonFrame(
id = 1:3,
name = c("Alice", "Bob", "Charlie"),
age = c(25, 30, 35),
is_student = c(TRUE, FALSE, TRUE)
)
print(persons)
# Invalid modification (throws error)
try(persons$id <- letters[1:3])
```
Additional options for `data.frame` validation:
```{r}
PersonFrame <- type.frame(
frame = data.frame,
col_types = list(
id = integer,
name = character,
age = numeric,
is_student = logical,
gender = enum("M", "F"),
email = function(x) all(grepl("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$", x))
),
freeze_n_cols = FALSE,
row_callback = function(row) {
if (row$age >= 40) {
return(sprintf("Age must be less than 40 (got %d)", row$age))
}
if (row$name == "Yanice") {
return("Name cannot be 'Yanice'")
}
return(TRUE)
},
allow_na = FALSE,
on_violation = "error"
)
df <- PersonFrame(
id = 1:3,
name = c("Alice", "Bob", "Charlie"),
age = c(25, 35, 35),
is_student = c(TRUE, FALSE, TRUE),
gender = c("F", "M", "M"),
email = c("alice@test.com", "bob_no_valid@test.com", "charlie@example.com")
)
print(df)
summary(df)
# Invalid row addition (throws error)
try(rbind(df, data.frame(
id = 4,
name = "David",
age = 50,
is_student = TRUE,
email = "d@test.com"
)))
```
### Enums
Define enums for categorical variables; these are safe to use to protect a value from being modified to invalid options. The `enum` function creates a generator which is then used to create the enum object. This can be used standalone or as part of an interface.
```{r enum}
Colour <- enum("red", "green", "blue")
# Create an enum object
colour <- Colour("red")
print(colour)
colour$value <- "green"
print(colour)
# Invalid modification (throws error)
try(colour$value <- "yellow")
# Use in an interface
Car <- interface(
make = enum("Toyota", "Ford", "Chevrolet"),
model = character,
colour = Colour
)
# Implement the interface
car1 <- Car(
make = "Toyota",
model = "Corolla",
colour = "red"
)
print(car1)
# Invalid implementation (throws error)
try(Car(
make = "Honda",
model = "Civic",
colour = "yellow"
))
# Invalid modification (throws error)
try(car1$colour$value <- "yellow")
try(car1$make$value <- "Honda")
```
## Conclusion
The `interface` package provides powerful tools for ensuring type safety and validation in R. By defining interfaces, typed functions, and typed `data.frame`s, you can create robust and reliable data structures and functions with strict type constraints. For more details, refer to the package documentation.
## License
This package is licensed under the MIT License.
## Citation
If you use this package in your research or work, please cite it as:
Mezquita, D. (2024). interface: A Runtime Type System. R package version 0.1.2. https://github.com/dereckmezquita/interface