Help for Declarative Macros

Hello everyone,

I want to create a programming interface to model math functions with their domains and codomains. To do so, I want to create Unary, Binary, Ternary, Quaternary and NAry operators structs.

I want to know if someone can help me to write the macro that will generate the code for each struct.

The signature of the macro should be something like this:

create_operator!(OPERATOR_NAME, (OPERATOR_DOMAIN), (OPERATOR_CO_DOMAIN));
create_operator!(UnaryOperator, (usize), (usize));
create_operator!(BinaryOperator, (usize, usize), (usize));

The code that should be generated is:

struct Unary<'r, F: Fn(usize) -> usize> {
  dom: &'r Range<usize>,
  co_dom: &'r Range<usize>,
  f: F
}
struct BinaryOperator<'r, F: Fn(usize, usize) -> usize> {
  dom: (&'r Range<usize>, &'r Range<usize>),
  co_dom: &'r Range<usize>,
  f: F
}

Thank's.

but will it contradict with the previous one if called twice? Maybe you can build a single struct using a vector or an array with a parameter instead.

BTW: you should avoid using temporary references in structs. In 99% of cases they are a huge mistake.

References are for referring to data that already has its own permanent storage somewhere else, and will make structs containing them unusable outside of the scope of the source of the storage. References also can't be used to create any new data. Rust's type for storing data "by reference" is Box, not &.

On top of that Range is small and trivially copyable, so &Range and especialy Box<Range> is slower to use than Range.

There's a fair amount of domain-specific details in your code snippet, so it might be easier if you try implementing your own create_operator!() macro and post questions on this forum if you get stuck.

There is a section from The Book that walks you through constructing your own declarative macros. For more advanced techniques, The Little Book of Rust Macros is something we link to all the time and for those who prefer a more hands-on approach. Rustlings also has a set of macros exercises you might want to check out, although it doesn't go into writing more complex macros.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.