Skip to content

Macro coding style #17

@o314

Description

@o314

Interesting talk at JuliaCon 2022 !

from the commented code @ https://github.com/platform-aware-programming/PlatformAware.jl/blob/master/src/quantifiers/atmost.jl

abstract type AtMostInf end                     # 0

multiplier_super = "Inf"
magnitude_ = ""
for magnitude in reverse(['n', 'u', 'm', ' ', 'K', 'M', 'G', 'T', 'P', 'E'])
    for multiplier in reverse([1, 2, 4, 8, 16, 32, 64, 128, 256, 512])
        magnitude_super = multiplier == 512 ? magnitude_ : magnitude   
        code = "abstract type AtMost" * string(multiplier) * magnitude * " <: AtMost" * string(multiplier_super) * magnitude_super * " end"        
        eval(Meta.parse(code)); println(code)
        multiplier_super = multiplier
    end
    magnitude_ = magnitude
end

abstract type AtMost0 <: AtMost1n end

One can derive a proper impl in macro land

abstract type AtMostInf end                     # 0
let mul_super = "Inf" ,
    mag_ = "" ;
    for mag in reverse(['n', 'u', 'm', ' ', 'K', 'M', 'G', 'T', 'P', 'E'])
        for mul in reverse([1, 2, 4, 8, 16, 32, 64, 128, 256, 512])
            mag_super = mul==512 ? mag_ : mag
            nm1 = Symbol("AtMost" * string(mul) * mag)
            nm2 = Symbol("AtMost" * string(mul_super) * mag_super)
            @eval abstract type $nm1 <: $nm2 end
            mul_super = mul
        end
        mag_ = mag
    end
end
abstract type AtMost0 <: AtMost1n end

Proof : open a julia session, run the previous code block and the next one

using Test
@test AtMost16G |> supertype == AtMost32G
@test AtMost128u |> supertype == AtMost256u
@test AtMost4P |> supertype == AtMost8P
@test AtMost256M |> supertype == AtMost512M

Obviously, the same thing does apply for AtLeast

BTW you should not call parse in macro but return quote ("must not" should be more appropriated :) )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions