A question about function

Hello,
Please consider the following code:

function print3lines()
    inn = open("input.txt", "r")
    print1(inn)    # read and print first line
    print2(inn)    # read and print second line
    print3(inn)    # read and print third line
    end

    function print1(in1)
        println(readline(in1))
    end

    function print2(in2)
        println(readline(in2))
    end

    function print3(in3)
        println(readline(in3))
    end

I changed the code as follows:

function print3lines()
    inn = open("input.txt", "r")
    print1(inn)    # read and print first line
    print2(inn)    # read and print second line
    print3(inn)    # read and print third line
    end

    function print1(in)
        println(readline(in))
    end

    function print2(in)
        println(readline(in))
    end

    function print3(in)
        println(readline(in))
    end

I changed in1, in2 and in3 to in and the output of both codes is the same. Why?

Thank you.

Could you describe the difference you expected? It’s unclear how to answer your question, as the behavior is simply consistent with Julia’s variable scope rules and appears in several other languages.

2 Likes

Hello,
I mean, all input arguments have the same name. Doesn’t this cause a problem?

Isn’t the code below better?

function print3lines(inn)
    print1(inn)   
    print2(inn)   
    print3(inn)   
    end

    function print1(in)
        println(readline(in))
    end

    function print2(in)
        println(readline(in))
    end

    function print3(in)
        println(readline(in))
    end

inn = open("input.txt", "r")
print3lines(inn)

The variable argument names have nothing to do with the names used in other functions. Else we wouldn’t be able to do things like

fnc1(x) = 1
fnc2(x) = x

the x in fnc1 has nothing to do with the x in fnc2 and vice versa.

6 Likes

Your print functions are all the same, you just have three identical functions with different names. You could simplify it to

function print3lines(input)
    print1(input)   
    print1(input)   
    print1(input)  
end

function print1(input)
    println(readline(input))
end

input = open("input.txt", "r")
print3lines(input)
1 Like

Input arguments in a method definition introduce new variables in that method’s scope, so there’s no conflict among separate methods. However, I would advise against making new variables named in because you lose access to the global function in, pretty useful.

but not the same, print1 != print2. I’m sure the redundancy is for a MWE.

2 Likes

I’m not so sure. Given the deep misunderstandings about naming going on, I found it worth pointing out.

1 Like