4

I am creating a non-standard string literal with a macro with something like that:

macro R13_str(p)
    rotate(13, p)
end

and it works. I can call it as:

R13"abc"

But I would like to declare the macro to work with any integer, like:

R1"abc"

or

R244"abc"

Let's say the function rotate() is:

function rotate(shift_amount::Int64, s::String)

    # Ensure the shift is no bigger than the string
    shift = shift_amount ≤ length(s) ? shift_amount : shift_amount % length(s)

    # Circular shift
    return s[end-shift+1:end] * s[1:end-shift]
end

How can I do that? I have checked all the docs, but it's not clear to me.

2 Answers 2

3

Can't see how to achieve exactly what is required. But the following might be good enough:

julia> macro R_str(p,flag)
           rotate(flag, p)
       end
@R_str (macro with 1 method)

julia> R"hello"3
"llohe"

julia> R"abc"1
"cab"

julia> R"abc"244
"cab"

See https://docs.julialang.org/en/v1/manual/metaprogramming/#meta-non-standard-string-literals

Trying to conform to OP call format:

julia> macro rework(expr)
       if expr.head != :macrocall return expr ; end
       r = String(expr.args[1])
       rr = parse(Int, r[3:findfirst('_',r)-1])
       :(rotate($rr, $(expr.args[3])))
       end
@rework (macro with 1 method)

julia> @rework R13"hello"
"llohe"

This macro could help to read the prepared test cases??

Sign up to request clarification or add additional context in comments.

2 Comments

Nice! Thank you, I believe that a flag could be a good solution. But I have a suite of tests like: R13"string" and R15"string" and I would need to declare 26 macros to e able to pass all the tests. That's why I was trying to achieve that.
@FlavioBarros Added another macro, which would perhaps get closer to support use case.
2

I have found a solution:

for n in 0:244
    @eval macro $(Symbol(:R, n, :_str))(s)
        rotate($n, s)
    end 
end

While I believe that using flags is the better approach, with this for loop I can generate all the macros that I need.

Julia> R1"abc" 
Julia> R24"acb" 
Julia> R56"abc"

simply work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.