Question

I'm pretty much fortran person. I'm losing my mind with a julia analog of cycle in fortran. By the way, goto statements doesn't work at this naive try:

x == y ? continue : goto mark1

mark1: 
println("hello")

It raises:

syntax: extra token "mark1" after end of expression
Was it helpful?

Solution

Within a function, @goto has now been implemented.

function example(y)
    for x in 1:1000
        x == y ? continue : @goto mark1
    end

    @label mark1
    println("hello")
end

See below for more information:



Although not traditionally considered loops, the @goto and @label macros can be used for more advanced control flow. One use case is when the failure of one part should lead to the retry of an entire function, often useful in input validation:

function getsequence()
    local a, b

@label start
    print("Input an integer: ")
    try
        a = parse(Int, readline())
    catch
        println("Sorry, that's not an integer.")
        @goto start
    end

    print("Input a decimal: ")
    try
        b = parse(Float64, readline())
    catch
        println("Sorry, that doesn't look numeric.")
        @goto start
    end

    a, b
end

However, this use case is often more clear using recursion:

function getsequence()
    local a, b

    print("Input an integer: ")
    try
        a = parse(Int, readline())
    catch
        println("Sorry, that's not an integer.")
        return getsequence()
    end

    print("Input a decimal: ")
    try
        b = parse(Float64, readline())
    catch
        println("Sorry, that doesn't look numeric.")
        return getsequence()
    end

    a, b
end

Although both examples do the same thing, the second is easier to understand. However, the first one is more performant (because it avoids the recursive call). In most cases, the cost of the call does not matter; but in limited situations, the first form is acceptable.

OTHER TIPS

I'm not entirely sure that this is a well-formed question, but there is an issue open for implementing local goto: https://github.com/JuliaLang/julia/issues/101. There's even a pull request with a prototype implementation, but it's gotten a little bit stalled.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top