LukasFun
LukasFun

Reputation: 229

When defined in a script, Julia functions don't print output

I have this Julia script:

function f(x,y)
    x+y
end

f(3, 4)

When I run this in the live terminal (via copy/paste), I get the desired result 7. But if I run the script, the output from the function is suppressed. Why is that?

Upvotes: 5

Views: 1643

Answers (1)

StefanKarpinski
StefanKarpinski

Reputation: 33290

Julia, unlike Matlab, doesn't automatically print values (the REPL does since that's what it's for: REPL = "read, eval, print loop"). You have to explicitly print the value using print or show, e.g. show(f(3, 4)). In this case, print and show do the same thing, but in general they have somewhat different meanings:

print([io::IO], xs...)

Write to io (or to the default output stream stdout if io is not given) a canonical (un-decorated) text representation. The representation used by print includes minimal formatting and tries to avoid Julia-specific details.

versus

show(x)

Write an informative text representation of a value to the current output stream. New types should overload show(io::IO, x) where the first argument is a stream. The representation used by show generally includes Julia-specific formatting and type information.

Note that there is also the @show macro, which prints the expression that is evaluated followed by its value, like so:

julia> @show f(3, 4);
f(3, 4) = 7

Upvotes: 5

Related Questions