Must the return value of a function be printed on the last line of the REPL? (when called without a `;`)

function f(x, y)
    s = x + y
    println("Look! The sum is $s.")
    return s

When I call this function with f(1, 2) the REPL prints:

julia> f(1, 2)
Look! The sum is 3.

But I want the function to print the result first and then print the concluding remark, and at the same time I want to let the sum s be the return value of function f.

Is that possible for Julia?

The function executes before the return value is available to display. So the only way to do what you want would be to capture the output, using e.g. the low-level redirect_stdout function or a higher-level package like IOCapture.jl, in order to save it to print later.

(Alternatively, of course, you can print whatever you want from the function itself, e.g. call display(s) before your println statement to mimic the REPL display, and then suppress additional output in the REPL by ending the line in a ;.)

1 Like

Thanks. I realized that the effect I am pursuing seems to have the awkward situation of self-reference, but it is indeed easy to achieve in other programming languages, such as matlab.

Can you give an example from another programming language of what you mean?

1 Like

Iā€™m sorry. It seems to be my fault. :disappointed_relieved:

Iā€™m not sure why it is your fault.

Do you actually need the return value?

If you return nothing then there is no display for thr return value,

julia> function f2(x, y)
           s = x + y
           println("Look! The sum is $s.")
           return nothing
f2 (generic function with 1 method)

julia> f2(1, 2)
Look! The sum is 3.

If you do need the return value, you can do this:

julia> r = Ref(0)

julia> g(ret, ref::Ref) = (ref[] = ret; nothing)
g (generic function with 1 method)

julia> g(f(1,2), r)
Look! The sum is 3.

julia> r[]

If you actually wanted to display 3 first, you can print it yourself.


Amazing! :smiley: Thanks!

I found what I really want to realize has been asked in another previous post by myself:

In general, I just want a function to output the calculation procedure and then give some conclusive statements (such as displaying the result as a graph), but also the user can easily obtain the result of the function (such as through the most conventional assignment statement).

In fact, I seem to have used some Julia functions (such as some functions for machine learning or optimization) that do have similar effects. :thinking: