debugging 是否有一个`dbg!`-like宏为朱莉娅?

xcitsw88  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(81)

Rust有一个非常方便的dbg!宏:

fn main() {
  dbg!(1 + 2);
}

上面的代码输出[src/main.rs:2] 1 + 2 = 3
有没有类似的朱莉娅?
我希望能够输出我的每一个结果,但是删除了函数后,只显示了最后一个没有函数的结果(而不是像MATLAB那样的所有结果)。

eit6fx6z

eit6fx6z1#

有一些内置的宏可以做到这一点:

julia> let x = 7
         @show x^2
         @info "cube of $x" x^3
         @warn "minus" -x maxlog=3
       end
x ^ 2 = 49
┌ Info: cube of 7
└   x ^ 3 = 343
┌ Warning: minus
│   -x = -7
└ @ Main REPL[42]:4

而第一个只是打印到stdout(例如参见@macroexpand @show x),宏@info@warn使用日志记录模块,该模块具有各种更复杂的功能,包括抑制一些调用站点的打印细节,(正如@BallpointBen提到的)也可以直接从特殊的宏@__MODULE__@__FILE__@__LINE__中获得。

gk7wooem

gk7wooem2#

@ mcabbet回答了这个问题(所以我把他的回答标记为接受),但我只是想添加几个片段来展示我想出的一些相关和方便的宏:
编辑:我已经根据@ mcabews在这个答案下面的评论中的建议更新了这些宏。

# Compact show
macro showc(exs...)
    blk = Expr(:block)
    for ex in exs
        push!(blk.args, :(println($(sprint(Base.show_unquoted,ex)*" = "),
        repr(begin local value = $(esc(ex)) end, context = :compact=>true) * "\n")))
    end
    isempty(exs) || push!(blk.args, :value)
    return blk
end

# Pretty show
macro showp(exs...)
    blk = Expr(:block)
    for ex in exs
        push!(blk.args, :(println($(sprint(Base.show_unquoted,ex)*" = "),
        repr(MIME("text/plain"), begin local value = $(esc(ex)) end, context = :limit=>true) * "\n")))
    end
    isempty(exs) || push!(blk.args, :value)
    return blk
end

给定以下变量:

PY1Y2 = [0.018 0.035 0.031 0.008 0.018;
         0.002 0.112 0.064 0.032 0.069;
         0.001 0.066 0.094 0.032 0.084;
         0.001 0.018 0.019 0.010 0.051;
         0.001 0.029 0.032 0.043 0.130];

d = PY1Y2[:, 1] ./ sum(PY1Y2[:, 1]);

@showp d;将显示:

d = 5-element Vector{Float64}:
 0.7826086956521738
 0.08695652173913043
 0.043478260869565216
 0.043478260869565216
 0.043478260869565216

@showc d;将显示:

d = [0.782609, 0.0869565, 0.0434783, 0.0434783, 0.0434783]

与内置的@show d;相比:

d = [0.7826086956521738, 0.08695652173913043, 0.043478260869565216, 0.043478260869565216, 0.043478260869565216]

相关问题