循环展开?朱莉娅与元编程

时间:2016-09-21 14:17:58

标签: metaprogramming julia loop-unrolling

有没有办法“元编程地”获得具有以下结构的代码块:

if r1 < R1
   s = 1

   elseif r1 < R2
      s = 2

      ... etc until N

   end
end

谢谢!

1 个答案:

答案 0 :(得分:3)

查看Base.Cartesian.@nif

我认为这对你有用......

julia> macroexpand(:(@nif 10 d->(r1 < R_d) d->begin s=d; break end))
:(if r1 < R_1 # REPL[9], line 1:
        s = 1 # REPL[9], line 1:
        break
    else
        if r1 < R_2 # REPL[9], line 1:
            s = 2 # REPL[9], line 1:
            break
        else
            if r1 < R_3 # REPL[9], line 1:
                s = 3 # REPL[9], line 1:
                break
            else
                if r1 < R_4 # REPL[9], line 1:
                    s = 4 # REPL[9], line 1:
                    break
                else
                    if r1 < R_5 # REPL[9], line 1:
                        s = 5 # REPL[9], line 1:
                        break
                    else
                        if r1 < R_6 # REPL[9], line 1:
                            s = 6 # REPL[9], line 1:
                            break
                        else
                            if r1 < R_7 # REPL[9], line 1:
                                s = 7 # REPL[9], line 1:
                                break
                            else
                                if r1 < R_8 # REPL[9], line 1:
                                    s = 8 # REPL[9], line 1:
                                    break
                                else
                                    if r1 < R_9 # REPL[9], line 1:
                                        s = 9 # REPL[9], line 1:
                                        break
                                    else  # REPL[9], line 1:
                                        s = 10 # REPL[9], line 1:
                                        break
                                    end
                                end
                            end
                        end
                    end
                end
            end
        end
    end)