Skip to content

Commit 848713a

Browse files
committed
Add macro based syntactic sugar for creating constant arrays
The syntax takes from the vec macro of rust standard library where the literal/expr followed by a ";" gives the value with which array is to be filled. A sequence of comma separated literals/exprs after ";" give the target shape of array.
1 parent df415e7 commit 848713a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/core/macros.rs

+30
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,25 @@ macro_rules! eval {
298298
};
299299
}
300300

301+
/// Create an array of given shape filled with a single value a.k.a constant array
302+
///
303+
/// # Examples
304+
///
305+
/// ```rust
306+
/// # use arrayfire::{constant};
307+
/// let _zeros_1d = constant!(0.0f32; 10);
308+
/// let _ones_3d = constant!(1u32; 3, 3, 3);
309+
///
310+
/// let dim = 10;
311+
/// let mix_shape = constant!(42.0f32; dim, 10);
312+
/// ```
313+
#[macro_export]
314+
macro_rules! constant {
315+
($value:expr; $($dim:expr),+) => {
316+
$crate::constant($value, $crate::dim4!($($dim),*))
317+
};
318+
}
319+
301320
#[cfg(test)]
302321
mod tests {
303322
use super::super::array::Array;
@@ -425,4 +444,15 @@ mod tests {
425444
eval!(a[indices, seq4gen] = b);
426445
// ANCHOR_END: macro_seq_array_assign
427446
}
447+
448+
#[test]
449+
fn constant_macro() {
450+
let _zeros_1d = constant!(0.0f32; 10);
451+
let _zeros_2d = constant!(0.0f64; 5, 5);
452+
let _ones_3d = constant!(1u32; 3, 3, 3);
453+
let _twos_4d = constant!(2u16; 2, 2, 2, 2);
454+
455+
let dim = 10;
456+
let _mix_shape = constant!(42.0f32; dim, 10);
457+
}
428458
}

0 commit comments

Comments
 (0)