How to correctly do line continuation in Julia? - julia

In fortran, we can simply use & to do line continuation.
But I wonder, in Julia, is there a safe way to do line continuation?
I heard that sometimes Julia cannot identify line continuation and it can cause bugs? Because after, Julia does not seem to have any symbol to do line continuation. Can Julia correctly recognize the line continuation?
Like I define the below function with long arguments,
function mean_covar_init(kmix::Int64,dim_p::Int64,weight::Array{Float64,1},sigma::Array{Float64,2},mu::Array{Float64,2})
return nothing
end
If I do things like
function mean_covar_init(kmix::Int64
,dim_p::Int64
,weight::Array{Float64,1}
,sigma::Array{Float64,2}
,mu::Array{Float64,2})
return nothing
end
Is it safe? Thank you very much!

If you do the thing like you have presented it is safe because Julia sees ( in the first line of code so it will look for a closing ).
However a problematic code would be:
f() = 1
+ 2
The reason is that the f() = 1 part is a valid and complete function definition. Therefore you need to make sure to signal Julia that the line is incomplete. The three most typical ways to do it are:
Move the + to the end of first line:
f() = 1 +
2
Use ( and ) as a wrapper:
f() = (1
+ 2)
Use begin and end:
f() = begin 1
+ 2 end
Let me give another example with macros, which do not require parenthesis or punctuation and therefore can be often tricky. Therefore the following:
#assert isodd(4) "What even are numbers?"
if rewritten as
#assert isodd(4)
"What even are numbers?"
does not produce what you expect, and you need to do e.g.:
#assert(isodd(4),
"What even are numbers?")

Related

How to prevent global variable or array in module?

I am coming from Fortran to Julia. I know in Julia want to prevent using global variables.
But the thing is, how to prevent using global variables in a module?
For example, in the following module,
module Mod
global AAA=zeros(1000000000)
function f(x)
change the most up to date AAA with x in some way.
return nothing
end
function g(x)
using the most up to date AAA, then change/update AAA with x in some way.
return nothing
end
end
In the above example, I need to update the very big array AAA, so I put AAA in the global. So f(x) and g(x) can use the most updated AAA and further update them.
Now since Julia discourage the use of global variable, so in my case, what do I do?
I mean, do I put AAA just in the argument of f(x) and g(x) such that they become f(x,AAA) and g(x,AAA)?
Is passing a very big array like AAA in the argument really faster than putting AAA just as a global variable?
It is possible to pass the array in question to the functions.
Here is an updated version of your pseudo code.
module Mod
AAA=zeros(1000000000)
function f!(ba, x) # the ! mark to indicate that ba will be updated
ba[1]=x
return nothing
end
function g!(ba, x)
ba[1] +=x
return nothing
end
function example()
f!(AAA,1)
g!(AAA,2)
#show(AAA[1])
end
end
I am using my phone, so there could be some typos, and I can't benchmark, but you could do it if you want to convince yourself there is no penalty in passing the array as an argument.
It is common practice to add a ! when the function mutates the content of the argument. Also, the arguments changed are put first in the list. Of course, these are only conventions, but it makes it easier for others to understand the intent of your code.

Julia iterator which parses each line in file

I'm new to Julia and have hit a rock with something I imagine should be a common scenario:
I would like an iterator which parses a text file one line at a time. So, like eachline(f), except a function parse is applied to each line. Call the result eachline(parse, f) if you wish (like the version of open with an extra function argument): mapping parse over eachline.
To be more specific: I have a function poset(s::String) which turns a string representation of a poset into a poset:
function poset(s::String)
nums = split(s)
...
return transitiveclosure(g)
end
Now I'd like to be able to say something like
open("posets7.txt") do f
for p in eachline(poset, f)
#something
end
end
(and I specifically need this to be an iterator: my files are rather large, so I really want to parse them one line at a time).
I think I would (personally) use for Iterators.map in such a case:
open("posets7.txt") do f
for p in Iterators.map(poset, eachline(f))
# do something
end
end
But, as the documentation notes (and as you discovered yourself), this is equivalent to using a generator expression:
open("posets7.txt") do f
for p in (poset(x) for x in eachline(f))
# do something
end
end

KEYWORD_SET in IDL

I am new to IDL and find the KEYWORD_SET difficult to grasp. I understand that it is a go no go switch. I think its the knocking on and off part that I am having difficulty with. I have written a small program to master this as such
Pro get_this_done, keyword1 = keyword1
WW=[3,6,8]
PRINT,'WW'
print,WW
y= WW*3
IF KEYWORD_Set(keyword1) Then BEGIN
print,'y'
print,y
ENDIF
Return
END
WW prints but print, y is restricted by the keyword. How do I knock off the keyword to allow y to print.
Silly little question, but if somebody can indulge me, it would be great.
After compiling the routine, type something like
get_this_done,KEYWORD1=1b
where the b after the one sets the numeric value to a BYTE type integer (also equivalent to TRUE). That should cause the y-variable to be printed to the screen.
The KEYWORD_SET function will return a TRUE for lots of different types of inputs that are basically either defined or not zero. The IF loop executes when the argument is TRUE.
Keywords are simply passed as arguments to the function:
get_this_done, KEYWORD1='whatever'
or also
get_this_done, /KEYWORD1
which will give KEYWORD1 the INT value of 1 inside the function. Inside the function KEYWORD_SET will return 1 (TRUE) when the keyword was passed any kind of value - no matter whether it makes sense or not.
Thus as a side note to the question: It often is advisable to NOT use KEYWORD_SET, but instead resort to a type query:
IF SIZE(variable, /TNAME) EQ 'UNDEFINED' THEN $
variable = 'default value'
It has the advantage that you can actually check for the correct type of the keyword and handle unexpected or even different variable types:
IF SIZE(variable, /TNAME) NE 'LONG' THEN BEGIN
IF SIZE(variable, /TNAME) EQ 'STRING' THEN $
PRINT, "We need a number here... sure that the cast to LONG works?"
variable = LONG(variable)
ENDIF

Tell if number is odd or even with SML

This is the second SML program I have been working on. These functions are mutually recursive. If I call odd(1) I should get true and even(1) I should get false. These functions should work for all positive integers. However, when I run this program:
fun
odd (n) = if n=0 then false else even (n-1);
and
even (n) = if n=0 then true else odd (n-1);
I get:
[opening test.sml]
test.sml:2.35-2.39 Error: unbound variable or constructor: even
val it = () : unit
How can I fix this?
The problem is the semicolon (;) in the middle. Semicolons are allowed (optionally) at the end of a complete declaration, but right before and is not the end of a declaration!
So the compiler is blowing up on the invalid declaration fun odd (n) = if n=0 then false else even (n-1) that refers to undeclared even. If it were to proceed, it would next blow up on the illegal occurrence of and at the start of a declaration.
Note that there are only two situations where a semicolon is meaningful:
the notation (...A... ; ...B... ; ...C...) means "evaluate ...A..., ...B..., and ...C..., and return the result of ...C....
likewise the notation let ... in ...A... ; ...B... ; ...C... end, where the parentheses are optional because the in ... end does an adequate job bracketing their contents.
if you're using the interactive REPL (read-evaluate-print loop), a semicolon at the end of a top-level declaration means "OK, now actually go ahead and elaborate/evaluate/etc. everything so far".
Idiomatic Standard ML doesn't really use semicolons outside of the above situations; but it's OK to do so, as long as you don't start thinking in terms of procedural languages and expecting the semicolons to "terminate statements", or anything like that. There's obviously a relationship between the use of ; in Standard ML and the use of ; in languages such as C and its syntactic descendants, but it's not a direct one.
I'm sure there's a didactic point in making these functions recursive, but here's some shorter ones:
fun even x = x mod 2 = 0
val odd = not o even

Confusion with ' operator and bracketing where (v')*v becomes Ac_mul_B despite overloading

I am playing around with the idea of CoVectors in Julia and am getting some behaviour I didn't expect from the parser/compiler. I have defined a new CoVector type that is the ctranspose of any vector, and is just a simple decoration:
type CoVector{T<:AbstractVector}
v::T
end
They can be created (and uncreated) with ' using ctranspose:
import Base.ctranspose
function CoVector(T::DataType,d::Integer=0)
return CoVector(Array(T,d))
end
function Base.ctranspose(cv::CoVector)
return cv.v
end
function Base.ctranspose(v::AbstractVector)
return CoVector(v)
end
function Base.ctranspose(v::Vector) # this is already specialized in Base
return CoVector(v)
end
Next I want to define a simple dot product
function *(x::CoVector,y::AbstractVector)
return dot(x.v,y)
end
Which can work fine for:
v = [1,2,3]
cv = v'
cv*v
returns 14, and cv is a CoVector. But if I do
(v') * v
I get something different! In this case it is a single element array containing 14. How come parenthesis doesn't work how I expect?
In the end we see the expression gets expanded to Ac_mul_B which defaults to [dot(A,B)] and it seems that this interpretation is defined at the "operator" level.
Is this expected behaviour? Can Julia completely ignore my bracketing and change the expression as it wants? In Julia I like that I can override things in Base but is it also possible to make self-consistent changes to how operators are applied? I see the expression doesn't have head call but Symbol call... does this change in Julia 0.4? (I read somewhere that call is becoming more universal).
I guess I can fix the problem by redefining Ac_mul_B but I was very surprised that it was called at all, given my above definitions.

Resources