Skip to content

Commit b6e46aa

Browse files
committed
Relax array(dim=) checks for reshape
1 parent 66ef931 commit b6e46aa

2 files changed

Lines changed: 37 additions & 5 deletions

File tree

R/r2f-constructors.R

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,13 +89,20 @@ r2f_handlers[["array"]] <- function(args, scope = NULL, ...) {
8989
# R semantics: `array()` flattens its input (dropping dim) then reshapes.
9090
# We implement this as `reshape()`; recycling is not supported here.
9191
dim_vec <- r2f(args$dim, scope, ...)
92-
if (is.null(dim_vec@value) || dim_vec@value@mode != "integer") {
93-
stop("array(dim=) must be an integer vector", call. = FALSE)
92+
if (
93+
is.null(dim_vec@value) ||
94+
!(dim_vec@value@mode %in% c("integer", "double"))
95+
) {
96+
stop("array(dim=) must be an integer/numeric value", call. = FALSE)
9497
}
95-
if (dim_vec@value@rank != 1L) {
96-
stop("array(dim=) must be a 1-d integer vector", call. = FALSE)
98+
shape <- if (passes_as_scalar(dim_vec@value)) {
99+
glue("[int({dim_vec})]")
100+
} else if (dim_vec@value@rank == 1L) {
101+
glue("int({dim_vec})")
102+
} else {
103+
stop("array(dim=) must be a scalar or 1-d vector", call. = FALSE)
97104
}
98-
out <- Fortran(glue("reshape({out}, int({dim_vec}))"), out@value)
105+
out <- Fortran(glue("reshape({out}, {shape})"), out@value)
99106
}
100107

101108
out@value <- Variable(

tests/testthat/test-array-reshape.R

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,28 @@ test_that("array() supports reshaping non-scalar data", {
88
x <- array(sample(1:10, 24, replace = TRUE), dim = c(2L, 3L, 4L))
99
expect_quick_identical(fn, list(x))
1010
})
11+
12+
test_that("array() reshape accepts numeric dim vectors", {
13+
fn <- function(x) {
14+
declare(type(x = integer(2L, 3L, 4L)))
15+
array(as.double(x), dim = c(2, 3, 4))
16+
}
17+
18+
set.seed(1)
19+
x <- array(sample(1:10, 24, replace = TRUE), dim = c(2L, 3L, 4L))
20+
expect_quick_identical(fn, list(x))
21+
})
22+
23+
test_that("array() reshape accepts scalar dims", {
24+
fn <- function(x) {
25+
declare(type(x = integer(24L)))
26+
# Rank-1 arrays carry a `dim` attribute in base R, but quickr treats them as
27+
# plain vectors; wrap in `c()` so both sides compare identically while still
28+
# exercising the `array(dim=scalar)` lowering.
29+
c(array(as.double(x), dim = 24))
30+
}
31+
32+
set.seed(1)
33+
x <- sample(1:10, 24, replace = TRUE)
34+
expect_quick_identical(fn, list(x))
35+
})

0 commit comments

Comments
 (0)