简体   繁体   English

朱莉娅:以循环宏为条件

[英]Julia: Conditional on For Loop Macros

Is there an easy way to change a "for loop header" depending on the packages a user has? 有没有一种简单的方法可以根据用户所拥有的软件包来更改“ for循环头”? For example, @progress for is good for adding a progress bar in Juno/Atom (just found out!), while we also have things like @simd, @acc, and @parallel. 例如,@ progress for很适合在Juno / Atom中添加进度条(刚刚发现!),而我们也有@ simd,@ acc和@parallel这样的东西。 So what I want to have on this loop is to put a bunch of these macros conditionally given a boolean from the user or depending on availability. 因此,我想在此循环中使用的是根据用户的布尔值或取决于可用性,有条件地放置一堆这些宏。 However, if I do a simple if isdefined(@progress) @progress for ... elseif accelerate @acc for ... elseif @parallel for ... end or something of that sort, I would have to keep pasting around the same for loop code. 但是,如果我if isdefined(@progress) @progress for ... elseif accelerate @acc for ... elseif @parallel for ... end进行简单的if isdefined(@progress) @progress for ... elseif accelerate @acc for ... elseif @parallel for ... end或类似的东西,则必须保持相同的粘贴状态。用于循环代码。 Is there some more elegant way of doing this? 有一些更优雅的方法吗? Also, I may want to combine some, and so once you start looking at the viable combinations that ends up being a lot of code! 另外,我可能想组合一些,所以一旦您开始研究可行的组合,最终导致很多代码!

The Pkg.installed method will error if the package isn't installed. 如果未安装软件包,则Pkg.installed方法将出错。 It takes a string, and returning the decorated expression after that line with the other possibility in the catch block is effective for this sort of thing: 它需要一个字符串,并在该行之后返回修饰的表达式以及catch块中的另一种可能性对这种情况有效:

macro optional_something(pkg, expr)
    try
        Pkg.installed(string(pkg)) == nothing && return expr
        esc(quote
            @time $expr
        end)
    catch
        expr
    end
end

# this won't add the macro @time
@optional_something XXX rand(1000)    

# this will
@optional_something Plots rand(1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM